Skip to content
Advertisement

I am fetching data of user where role equals to teacher , status is active and other orWhere. This collection gives me super admin user also but why?

$data['tutors'] = User::where('status', 'active')
                ->whereRelation('role','name', 'teacher')
                ->where('name', 'like', "%" . $req . "%")
                ->where('first_name', 'like', "%" . $req . "%")
                ->orWhere('last_name', 'like', "%" . $req . "%")
                ->orWhere('description', 'like', "%" . $req . "%")
                ->orWhereRelation('country','name', 'like', "%" . $req . "%")
                ->orWhereRelation('state','name', 'like', "%" . $req . "%")
                ->orWhereRelation('city','name', 'like', "%" . $req . "%")
                ->orWhereRelation('languages.language','name', 'like', "%" . $req . "%")
                ->orWhereRelation('gigs','title', 'like', "%" . $req . "%")
                ->orWhereRelation('gigs','price', 'like', "%" . $req . "%")
                ->orWhereRelation('gigs','description', 'like', "%" . $req . "%")
                ->orWhereRelation('skills.skill','name', 'like', "%" . $req . "%")
                ->with('languages.language')
                ->with('skills.skill')
                ->with('country')->paginate(5);

I am working on search. I am facing issue with the query. when ever i search super. It gives me super admin user also but i am using ->whereRelation('role','name', 'teacher')

Advertisement

Answer

that because if any orWhere come with true, the record will be fetched, you should group your orWhere in one statment:

$data['tutors'] = User::where('status', 'active')
            ->whereRelation('role','name', 'teacher')
            ->where(function ($query) use ($req) {
                $query->where('name', 'like', "%" . $req . "%")
                    ->orWhere('first_name', 'like', "%" . $req . "%")
                    ->orWhere('last_name', 'like', "%" . $req . "%")
                    ->orWhere('description', 'like', "%" . $req . "%")
                    ->orWhereRelation('country','name', 'like', "%" . $req . "%")
                    ->orWhereRelation('state','name', 'like', "%" . $req . "%")
                    ->orWhereRelation('city','name', 'like', "%" . $req . "%")
                    ->orWhereRelation('languages.language','name', 'like', "%" . $req . "%")
                    ->orWhereRelation('gigs','title', 'like', "%" . $req . "%")
                    ->orWhereRelation('gigs','price', 'like', "%" . $req . "%")
                    ->orWhereRelation('gigs','description', 'like', "%" . $req . "%")
                    ->orWhereRelation('skills.skill','name', 'like', "%" . $req . "%");
            })
            ->with('languages.language')
            ->with('skills.skill')
            ->with('country')->paginate(5);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement