Reputation: 39
I need to get filtered data from many to many relationship from Post and Tag tables.
I have Post Model:
class Post extends Model
{
public function tag()
{
return $this->belongsToMany('App\Tag', 'post_tag','post_id','tag_id');
}
}
And Tag Model like:
Class Tag extends Model
{
protected $fillable = ['name'];
public function post()
{
return $this->belongsToMany(Post::class, 'post_tag');
}
}
But when I try to get filtered data based on tag_id:
if($request->filled('tag_id')){
$posts = Post::whereHas(
['tag' => function($query) use($request)
{
$query->where('tag_id','=', $request->input('tag_id'));
}
])->get();
}
It doesnt work
Upvotes: 1
Views: 31
Reputation: 12188
according to laravel doc
whereHas take string and callback function as parameters not an array:
$posts = Post::whereHas(
'tag' ,function($query) use($request)
{
$query->where('tag_id','=', $request->input('tag_id'));
}
)->get();
Upvotes: 1