Skip to main content
Tutorial Free

Filtering query results with different conditions on the same page

October 22, 2015
1 min read
Title of the article might sound unclear, but let's imagine you have customer list from Customer::all(), but then you need two separate lists/tables - customers from UK and from US. How to avoid two queries here? There's a filter() function. So, you're doing like this as usual:
$customers = Customer::all();
And then you can filter the results, passing your own closure function to describe condition.
$uk_customers = $customers->filter(function ($customer) {
    return $customer->country == 'United Kingdom';
});
Now, at this point you have a new collection in $uk_customers variable, but the old $customers will remain the same, unchanged. With this in mind, we can add another filter:
$us_customers = $customers->filter(function ($customer) {
    return $customer->country == 'United States';
});
So, now you have two separate lists in $uk_customers and $us_customers and you can view them in separate tables. There's also an opposite function called reject() - for example, if you want to keep all records EXCEPT United Kingdom, this is how it would look:
$non_uk_customers = $customers->reject(function ($customer) {
    return $customer->country == 'United Kingdom';
});
That's it - another short, but useful tip.

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

[NEW] Building a Typical Laravel SaaS

11 lessons
1 h 36 min

PhpStorm Junie AI for Laravel Projects: Crash Course

7 lessons
36 min

NativePHP: Build Mobile App with Laravel

11 lessons
2 h 2 min read

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.