Filtering query results with different conditions on the same page

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.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials