Home > Back-end >  trying to search in a table or in its relation in laravel
trying to search in a table or in its relation in laravel

Time:10-31

I need to search for the code in the appointment table OR the patient name which is the appointment's relation. here is the code I reached so far but it is not working:

$lab = Lab::with(['patient' => function ($q) use ($search_query) {
        $q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
            ->where('name', 'like', "%{$search_query}%")
            ->orWhereRaw("concat(first_name, ' ', second_name) like '%$search_query%' ")
        );
    }])
        ->select('id', 'code')
        ->Where('code', 'like', "%{$search_query}%")
        ->limit(5)
        ->get();

CodePudding user response:

Loding relation is different from applying 'where' on it, you sould load the relation and apply 'whereHas' in another statement:

 $lab = Lab::with(['patient' => function ($q) {
            $q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
            );
        }])
            ->select('id', 'code')
            ->Where('code', 'like', "%{$search_query}%")
            ->orWhereHas('patient',function ($query) use ($search_query) {
                $query->where('name', 'like', "%{$search_query}%");
            })
            ->limit(5)
            ->get();
  • Related