During the daily development process of Laravel, we often encounter scenarios where "invalid" data in the array need to be cleaned. For example, fields that are not filled in the form, values that are empty in API parameters, or data items need to be filtered based on certain logic. In PHP, array_filter() is a powerful tool to deal with these problems.
Although array_filter() is a native PHP function, it also has a very wide application scenario in the Laravel project. Next, we will take you step by step through a few real examples to use it gracefully in your Laravel project.
One of the most common scenarios is when the user submits a form, but some fields are empty. We want to only process non-empty fields.
$data = [
'name' => 'Alice',
'email' => '',
'phone' => null,
'age' => 25,
];
// use array_filter Filter empty values(It will be removed by default false、null、''、0)
$filtered = array_filter($data);
dd($filtered);
Output:
[
'name' => 'Alice',
'age' => 25,
]
In Laravel, this processing is often used to clean up after receiving requested data in the controller:
public function store(Request $request)
{
$data = array_filter($request->only(['name', 'email', 'phone', 'age']));
// The following logic only processes non-empty fields
User::create($data);
return redirect()->to('https://m66.net/success');
}
The default array_filter() removes all "false values", including the number 0 and the string "0". What if you just want to remove empty strings and keep valid 0s?
$data = [
'status' => 0,
'code' => '0',
'description' => '',
];
// Custom callbacks,Filter only empty strings
$filtered = array_filter($data, function ($value) {
return $value !== '';
});
Output:
[
'status' => 0,
'code' => '0',
]
This writing method is very practical in handling order status, price range and other logic, avoiding the error deletion of effective "0".
Laravel's Collection also provides a similar filter() method, similar to array_filter() , but more powerful. For example, we can operate in a chain:
$users = collect([
['name' => 'Tom', 'email' => 'tom@m66.net'],
['name' => 'Jerry', 'email' => null],
['name' => 'Spike', 'email' => ''],
]);
$filtered = $users->filter(function ($user) {
return !empty($user['email']);
});
You can also use filter() directly to simplify the logic:
$filtered = $users->filter(fn($user) => !empty($user['email']));
Output:
[
['name' => 'Tom', 'email' => 'tom@m66.net'],
]
Suppose you are developing a user search function, and the front end passes some optional parameters, and you just want to build a query containing non-empty conditions:
public function index(Request $request)
{
$filters = array_filter($request->only(['name', 'email', 'status']), function ($val) {
return $val !== '';
});
$users = User::where($filters)->get();
return view('users.index', compact('users'));
}
In this way, you can flexibly build query conditions based on actual input to avoid invalid queries such as where('', '') .
array_filter() is a simple but very powerful tool. When used with Laravel's Request and Collection, it can greatly improve the efficiency of data cleaning and code readability.
If you haven't used array_filter() in your project, you might as well try it now and make it a good helper when writing Laravel!