How to make a filter in Laravel for multiple parameters?

/
/
/
817 Views

There are many ways to make a filter in Laravel. In this article, we will show you the two best ways.

  1. Build your own filter by using your own logic. This method will help you in complex conditions.
$result = Post::query();

if (!empty($text)) {
    $result = $result->where('text', 'like', '%'.$text.'%');
}

if (!empty($date)) {
    $result = $result->whereDate('created_at', \Carbon\Carbon::parse($date));
}

if (!empty($category)) {
    $result = $result->where('category', $category);
}

if (!empty($city)) {
    $result = $result->where('city', 'like', '%'.$city.'%');
}

$result = $result->get();

2. Using when clause in Laravel

Post::when($text, function ($q) use ($text) {
        return $q->where('text', 'like', '%'.$text.'%');
    })
    ->when($date, function ($q) use ($date) {
        return $q->whereDate('created_at', \Carbon\Carbon::parse($date));
    })
    ->when($category, function ($q) use ($category) {
        return $q->where('category', $category);
    })
    ->when($city, function ($q) use ($city) {
        return $q->where('city', 'like', '%'.$city.'%');
    })
    ->get();

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar