I have a problem with how to select article by category name with laravel eloquent. My index function in controller:
$article = Article::with('category')->when(request()->q, function($article) {
$article->where('category.name', 'like', '%'. request()->q . '%');
})->latest()->paginate(10);
this code return error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category.name' in 'where clause'
My article model is already set to belongs category
public function category()
{
return $this->belongsTo(Category::class,"category_id");
}
But im not wonder its still not working. Thanks for your help.
$article = Article::with('category')
->when(request()->q, function($article) {
$article->whereHas('category',
fn($q) => $q->where('name', 'like', '%'. request()->q . '%')
);
})
->latest()
->paginate(10);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.