Laravel: searching relationships with conditions and retrieving the records

Your original query is restricted with whereHas() to instances of StdActs that meet the requirements, but you don’t ask to eager load the relationship. This is done using the with() method, and then we constrain that with the same requirements as before.

$key     = '%' . request('keywords') . '%';
$year    = request('year');
$school  = request('school');

$stdActs = StdActs::where('year_id', $year)
    ->where('school_id', $school)
    ->whereHas('student', fn ($q) => $q->where('std_name', 'like' , $key))
    ->with(['student' => fn ($q) => $q->where('std_name', 'like' , $key)])
    ->get();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top