Ad

Laravel Eloquent How To Apply Condition On "with" Datas On The Output?

here my code :

$prestations = Prestation::with(
            [
            'service' => function($service) use($searchService) {
                $service->select(['id','name'])->where('name', 'regexp', "/$searchService/i");
            },
            'facility' => function($facility) use($searchPartenaire) {
                $facility->select(['id','name'])->where('name', 'regexp', "/$searchPartenaire/i");
            }
            ]
        )
            ->where('name', 'regexp', "/$search/i")
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

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

The problem is that in the output of all datas where "service" and "facility" names are not equal on the $searchService and $searchPartenaire the values are replaced by "null". So i don't want to have values in the output where the search variables are not equals.

Thank you.

Ad

Answer

you can try like this

 $prestations = Prestation::with('service','facility');

        $prestations->whereHas('service', function ($query) use ($searchPartenaire) {
            $query->Where('name', 'like', '%' . $searchPartenaire . '%');
        });

        $prestations->whereHas('facility', function ($query) use ($searchPartenaire) {
            $query->Where('name', 'like', '%' . $searchPartenaire . '%');
        });

        $prestations->where('name', 'like', '%'.$search.'%')
            ->orderBy($orderBy, $orderDirection)
            ->simplePaginate(50);

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

1st create instances of Prestation$prestations = Prestation::with('service','facility')

then apply the condtion this is good approach in seach

Ad
source: stackoverflow.com
Ad