How can I use a many-to-many relationship to display articles by tag in Laravel?

Updated: Feb 09, 2025

How can I use a many-to-many relationship to display articles by tag in Laravel?

To display articles by tag using a many-to-many relationship in Laravel, follow these steps:

  1. Define the many-to-many relationship in your models:

Assuming you have two models, Article and Tag, both with id fields.

In app/Article.php:

public function tags()
{
    return $this->belongsToMany(Tag::class);
}

In app/Tag.php:

public function articles()
{
    return $this->belongsToMany(Article::class);
}
  1. Migrate your database:

Run the following command to create the pivot table for the many-to-many relationship:

php artisan make:migration create_article_tag_table --table=article_tag --create=article_tag

Edit the generated migration file database/migrations/xxxx_xx_xx_xxxxxx_create_article_tag_table.php:

public function up()
{
    Schema::create('article_tag', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('article_id');
        $table->unsignedBigInteger('tag_id');
        $table->timestamps();

        $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
        $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
    });
}

Run the migration:

php artisan migrate
  1. Access articles by tag:

Now you can access articles by tag using the defined relationship. For example, to get all articles with a specific tag, use:

$tag = Tag::find(1);
$articles = $tag->articles;

Or to get all articles with multiple tags:

$tags = Tag::find(1, 2, 3)->load('articles');
$articles = $tags->flatMap->articles;

This will return a collection of articles that have the specified tags.