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

tnort's avatar
Level 4

Laravel product query filter

Hi all,

I am looking to build a query that would filter my products based on some input checkbox selectors.

$courses = Course::with('level', 'campus')->where('university_id', $university->id)->where('name', 'LIKE', '%'.$request->search.'%')->whereIn('levels', $request->levels)->paginate(10);

it works just fain when $request->levels is set but would fail when is not set.

Also tried to build a query through the DB Facade DB::select('select * from courses where university_id = ? ', [$university->id]) but then I realised I cannot attach the pagination or at least I'll have to convert the array in a collection and to it manually.

Also, there might be a different solution where I fetch on the server all courses and then filter them using PHP.

I would be very grateful if you could help here, thank you.

0 likes
2 replies
MichalOravec's avatar
Level 75

Use conditional clauses

$courses = Course::with('level', 'campus')
    ->where('university_id', $university->id)
    ->when($request->search, function ($query, $search) {
        return $query->where('name', 'LIKE', "%{$request->search}%");
    })
    ->when($request->levels, function ($query, $levels) {
        return $query->whereIn('levels', $levels);
    })
    ->paginate(10);

https://laravel.com/docs/9.x/queries#conditional-clauses

And most likely you can use relationship to get courses by university.

$courses = $university->courses()
    ->with('level', 'campus')
    ->get();

*I skipped other where queries.

1 like

Please or to participate in this conversation.