Ad

Laravel Eloquent Use The OrWhere Query In My Search System Request

I tried to code a request with search system. Here the code:

$search = request()->get('search');
if(Auth::user()->hasRole('admin') || true) 
{
  list($orderBy, $orderDirection) = explode('.', request()->get('sort_by'));
  $prestations = Prestation::with(
    'service:id,name',
    'facility:id,name'
  )
  ->orWhere('service:name', 'regexp', "/$search/i")
  ->orderBy($orderBy, $orderDirection)
  ->simplePaginate(50);

  $res = [
    'results' => $prestations,
    'total' => Prestation::all()->count(),
  ];

  return $res;
}

The problem is that I don't know how to do something like I tried with the orWhere -> get all service name (from the relationship "with") which are equal to my $search.

Thank you.

Ad

Answer

Try this query.

$prestations = Prestation::with(
                [
                'service' => function($service) use($search){
                    $service->select(['id','name'])->where('name', $search);
                },
                'facility' => function($facility) {
                    $facility->select(['id','name'])
                }
                ]
            );
Ad
source: stackoverflow.com
Ad