Skip to content

Instantly share code, notes, and snippets.

@aquasmit
Last active August 23, 2021 04:00
Show Gist options
  • Save aquasmit/e0edae8b24fad18a4ddf3957c79cfd0d to your computer and use it in GitHub Desktop.
Save aquasmit/e0edae8b24fad18a4ddf3957c79cfd0d 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);
@mahdihassani12
Copy link

How to pass categories.id to the function:
$posts = Posts::whereHas('categories', function($q) use($slug){
$q->where('categories.id', 11); //How to pass this id inside function?

	     })
                >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