Search Laravel's JSON columns in other tables via association
P粉596161915
P粉596161915 2024-02-26 20:25:23
0
1
441

I tried writing search code, this is my code:

$services = Service::query()->with('plans')->latest();


    if ($request->service_name) {
               $services = $services->whereRaw("CONVERT(JSON_EXTRACT(name, '$.ar') using 'utf8') LIKE '%$request->service_name%' ")
                ->orWhereRaw("CONVERT(JSON_EXTRACT(name, '$.en') using 'utf8') LIKE '%$request->service_name%' ")
                ->orWhereRaw("CONVERT(JSON_EXTRACT(name, '$.he') using 'utf8') LIKE '%$request->service_name%' ");
    }

        if ($request->plan_name) {
            $plan_name = $request->plan_name;
            $services = $services->whereHas('plans', function ($q) use ($plan_name) {
                $q->where('name->en','Like','%'.$plan_name.'%');
            });
       }

        return $services->get();

But when I send plan_name in the request, the code filters by service name instead of plan name

I tried filtering the data by plan name when sending the plan name code in the request but it doesn't work

P粉596161915
P粉596161915

reply all(1)
P粉807471604
if ($request->service_name && !$request->plan_name) { // When only service name provided
    $services = $services->whereRaw("CONVERT(JSON_EXTRACT(name, '$.ar') using 'utf8') LIKE  '%$request->service_name%' ")
            ->orWhereRaw("CONVERT(JSON_EXTRACT(name, '$.en') using 'utf8') LIKE  '%$request->service_name%' ")
            ->orWhereRaw("CONVERT(JSON_EXTRACT(name, '$.he') using 'utf8') LIKE  '%$request->service_name%' ");
}

if ($request->plan_name && !$request->service_name) { // When only plan name provided
    $plan_name = $request->plan_name;
    $services = $services->whereHas('plans', function ($q) use ($plan_name) {
        $q->where('name->en','Like','%'.$plan_name.'%');
    });
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template