Callum
Callum

Reputation: 1165

Laravel Eloquent search multiple fields and relationship

I am trying to create a search query so that I can search the same string across a few different fields. The query also needs to search fields from the machine_warranties which is setup as a hasOne relationship on the Machines model.

Here's the warranty relationship in the Machines model

public function warranty()
{
    return $this->hasOne('App\MachineWarranty', 'machine_id');
}

Here's my attempt at the query. Searching for a serial or machine type works fine but I cannot figure out how to also search the relation.

Machine::orderBy('created_at', 'desc')
  ->where('serial', 'LIKE', '%' . $search . '%')
  ->orWhere('type', 'LIKE', '%' . $search . '%')
  ->with(['warranty' => function($query) use ($search) {
       $query->where('first_name', 'LIKE', '%' . $search . '%');
  }]);

Is there a way to do ->orWith() maybe?

Upvotes: 2

Views: 11642

Answers (2)

Sohel0415
Sohel0415

Reputation: 9863

Use whereHas() to make and query:

Machine::orderBy('created_at', 'desc')
->where('serial', 'LIKE', '%' . $search . '%')
->orWhere('type', 'LIKE', '%' . $search . '%')
->with('warranty')
->whereHas('warranty' , function($query) use ($search) {
   $query->where('first_name', 'LIKE', '%' . $search . '%');
})->get();

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163978

Use the orWhereHas() method:

Machine::latest()
    ->where('serial', 'like', '%' . $search . '%')
    ->orWhere('type', 'like', '%' . $search . '%')
    ->orWhereHas('warranty', function($q) use($search) {
        $q->where('first_name', 'like', '%' . $search . '%');
    })
    ->get();

Upvotes: 4

Related Questions