Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielchikaka/1578105185eb3641ed4d68fc44863d7e to your computer and use it in GitHub Desktop.
Save danielchikaka/1578105185eb3641ed4d68fc44863d7e to your computer and use it in GitHub Desktop.
Laravel - Eloquent - query many to many relationship

Laravel - Eloquent - query many to many relationship

Example:

Table 1: posts

Table 2: categories

Pivot Table: category_post with foreign keys category_id, post_id

Model File: Post.php

.....
public function categories()
{
    return $this->belongsToMany('App\Categories','category_post','post_id','category_id');
}

Model File: Category.php

.....
    public function posts()
    {
        return $this->belongsToMany('App\Posts','category_post','category_id','post_id');
    }    

Eloquent in Controller

So below Eloquent will fetch 5 records where categoty_id = 11

.....
     		$posts = Posts::whereHas('categories', function($q) use($slug){

    			               $q->where('id', 11); //this refers id field from categories table

		             })
                 ->where('type','post')
                 ->where('active',1)
                 ->orderBy('post_date','desc')
                 ->paginate(5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment