How to select article by category name with Laravel Eloquent

Viewed 15

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.

1 Answers
$article = Article::with('category')
    ->when(request()->q, function($article) {
        $article->whereHas('category',
            fn($q) => $q->where('name', 'like', '%'. request()->q . '%')
        );
    })
    ->latest()
    ->paginate(10);
Related