Ad

Laravel Eloquent, Apply Select On My Queries In WhereHas

Here my code :

$prestations = Prestation::with('service','facility','conciergeries.network')
            ->whereHas('service', function ($query) use ($searchService) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchService/i");
            })  
            ->whereHas('facility', function ($query) use ($searchPartenaire) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchPartenaire/i");
            })
            ->whereHas('conciergeries.network', function ($query) use ($searchFiliale) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchFiliale/i");
            })
                ->where('name', 'regexp', "/$search/i")
                ->orderBy($orderBy, $orderDirection)
                ->paginate(50);

I want get only names and ids of "service", "facility" and "conciegeries.network". I tried to use select('id','name'); and select(['id','name']); or addSelect('id','name'); and pluck('id', 'name'); but i get all datas. Do you have alternatives solutions ? Thank you !

Ad

Answer

Select needs to be added to with, not whereHas. Try this instead:

Prestation::with(['service' => function($query) { $query->select(['id','name']);},
    'facility' => function($query) { $query->select(['id','name']);},
    'conciergeries.network' => function($query) { $query->select(['id','name']);}
])
Ad
source: stackoverflow.com
Ad