How to query related records only using where clause in laravel?

I tried to search for students belonging to a specific user / school only using the following query. I created a one-to-many relationship between the user and the students. Everything looks fine, but when I try to search for students, it gives me a list of students belonging to other users.

public function searchStudent(Request $request)
{
    $q = $request->q;
    $grades = Auth::user()->grades;
    $searchPupils = Student::where('user_id','=',Auth::user()->id)->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();

    if(count($searchPupils) > 0)
    {
        return view('add-class', compact('grades'))->withDetails($searchPupils)->withQuery($q);
    }
    else
    {
        return view ('add-class', compact('grades'))->withMessage('No Details found. Try to search again !');
    }
}

I also tried to do

$searchPupils = Auth::user()->students()->where('name','LIKE','%'.$q.'%')->orWhere('email','LIKE','%'.$q.'%')->get();

Nevertheless, he is looking for the entire students table. How to do it?

+4
source share
1 answer
  • the problem is in your request where the conditions are, use the where option, as shown below.

    $searchPupils =Student::where('user_id','=',Auth::user()->id)
                ->where(function($query)use($q){
                       $query->where('name','LIKE','%'.$q.'%')
                            ->orWhere('email','LIKE','%'.$q.'%');
                  })->get();
    
+2
source

Source: https://habr.com/ru/post/1676437/


All Articles