Laravel Search BelongsTo

Viewed 66

I am making a search feature, and I am using orWhere, however, I've come to an issue where I want to search the brand_id by text. In my modal, I have it set to belongsTo but is there any way for me to use this in the MySQL search term?

My search query

$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
->orWhere('price', 'LIKE', '%' . $searchTerm . '%')->paginate(15);

I'd like to somehow include the brand name, not the brand_id I have in the database. Is there any way of doing this? I have it linked up like this in my Product model

public function brand()
{
    return $this->belongsTo(Brand::class);
}
1 Answers

You can use orWhereHas:

$products = Product::where('name', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('title', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('description', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('allergies', 'LIKE', '%' . $searchTerm . '%')
                ->orWhere('price', 'LIKE', '%' . $searchTerm . '%')
                ->orWhereHas('brand', function($q) use ($searchTerm){
                    $q->where('name', 'LIKE', "%{$searchTerm}%");
                })
                ->paginate(15);

https://laravel.com/docs/master/eloquent-relationships#querying-relationship-existence

Related