Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mawunyo's avatar

Where retrun null if using wherehas after in laravel query

Where retrun null if using wherehas after in laravel query

This ->where('name', 'LIKE', '%'.$schoolname.'%') return nothing. Why?

public function listecoles(){

    $schoolname = request()->query('query');
    $location = request()->query('location');
    $type = request()->query('type');


    if($schoolname || $location || $type){

        $schools = School::with('types')
                    
                ->where('name', 'LIKE', '%'.$schoolname.'%')
            
                ->whereHas('ville', function ($query) use ($location) {
                    $query->where('name', $location);
                })

                ->orWhereHas('quartier', function ($query) use ($location) {
                    $query->where('name', $location);
                })
                
            ->paginate(10);   
            //return response()->json($schools);            
    }else{
        $schools = School::paginate(6); 
    }

    return view('frontend.liste-ecoles')
    ->with('statuts', Statut::all())
    ->with('types', Type::all())
    ->with('schools', $schools);      
   
}
0 likes
2 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

Perhaps break this down to individual steps, make sure each step works before putting all together. Also look at whereHas in docs again for exact usage.

Snapey's avatar

if you want to use multiple where statements, you have to consider which ones should be grouped together

for example a and b or c is different to a and (b or c)

If you need to group where statements, you have to use a closure.

https://laravel.com/docs/5.8/queries#parameter-grouping

        $schools = School::with('types')
                    
                ->where('name', 'LIKE', '%'.$schoolname.'%')
            
                ->where(function ($query) use($location) {

                    $query->whereHas('ville', function ($query) use ($location) {
                        $query->where('name', $location);
                    })

                    ->orWhereHas('quartier', function ($query) use ($location) {
                        $query->where('name', $location);
                    })

               })                
                ->paginate(10);   

and then check each condition to make sure you actually have data in the database matching one of these conditions.

As suggested, start small and add one condition at a time

2 likes

Please or to participate in this conversation.