mercredi 27 février 2019

How to query a model and its related model in laravel

I am building a Laravel 5.5 project where i have 2 related models, User and Service with a relationship like so: Inside User.php

public function service()
{
  return $this->hasMany('App\Service');
}

and inside Service.php

public function user()
{
  return $this->belongsTo('App\User');
}

I need to query the service model for a service column where the query is either service_name or the name of a user. In effect, the query will search for the item in the service model and the related user model. I have written the query below but its returning an empty collection:

$items = Service::where('service_name', 'LIKE', "%".$query."%")
                 ->whereHas('user', function($q) use ($query){
                  $q->where('name', 'LIKE', "%".$query."%");))->get();

What am i doing wrong?

NB: My search on google, stackoverflow and laravel documentation didn't give exactly what i need hence my question please.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire