Q:

Querying a relation in Laravel

I'm trying to extend my site search. You can search for a title or in the description of an offer right now. Every offer has a subject. The subject has a name. I want to search for the subject name, too, but I can't it working.
This is how far I tried:
$adverts = Advert::orderBy('created_at', 'desc')->active();

  if($search)
    $adverts = $adverts->whereHas('subjects', function($q) use ($search)
    {
      $q->where('name', 'like', '%$search%');
    })
    ->where(function($query) use ($search) {
        $query->where("title", "like", "%$search%");
        $query->orWhere("description", "like", "%$search%");
    })
    ->get();

There's nothing broken, but the query does not find any Offers with the subject name like the search. 
Do you have any suggestions?
Thank you

A:

The default boolean operator for the where function in Laravel is AND. That means your code is actually saying:

Where the name contains $search AND title or the description contains $search

Obviously what you want is an OR in there.
So simply change the where after whereAs to orWhere.
$adverts = $adverts->whereHas('subjects', function($q) use ($search)
{
  $q->where('name', 'like', '%$search%');
})
->orWhere(function($query) use ($search) {
    $query->where("title", "like", "%$search%");
    $query->orWhere("description", "like", "%$search%");
})
->get();

