Laravel Check if Array is empty
Stefan Izdrail
Founder & Senior Architect · 2026-06-29
Title: Laravel Check if Array is empty: A Comprehensive Guide for Developers
Body:
Checking the emptiness of an array in PHP/Laravel is a common programming task. Your code may not be working due to various reasons, such as unclear syntax or the misuse of array functions. This guide aims to provide you with a comprehensive understanding of Laravel array functions and best practices for checking if an array is empty.
The Problem Code
@foreach($restaurantmenue as $daily)
@foreach($daily->articles as $menue)
@if(!empty($menue->title))
<div class="card card-horizontal">
...
@else
No Articles for Today
@endif
@endforeach
@endforeach
The Correct Syntax and Best Practices
1. Check array emptiness with Laravel's built-in `count` method:@if(count($array))
// Array is not empty, perform actions
@else
// Array is empty, display alternate content
@endif
2. Use Laravel's collection functions to check array emptiness:
@if(collect($array)->isNotEmpty())
// Collection has elements
@elseif(collect($array)->isEmpty())
// Collection is empty
@else
// Other condition if the above are not met (empty vs. non-collection)
@endif
3. Check array emptiness using the `count_values` function:
@if(count(array_count_values($array)) == 0)
// Array is empty
@else
// Array has elements
@endif
4. Utilize Laravel's built-in functions: `has` and `whereHas` for checking array relationships:
@if($model->restaurantmenue()->exists())
// Relationship exists
@else
// No related records found
@endif
Common Mistakes and Solutions
1. Incorrect syntax: Ensure you use the proper control flow constructs, such as `if` statements, to check your conditions correctly.@if(count($array))
// Array is not empty
@else
// Array is empty
@endif
2. Using the wrong array function: Double-check the documentation and examples for the appropriate Laravel functions to use, such as `collect`, `array_count_values`, or `has`/`whereHas` for specific use cases.
3. Unclear logic: Make sure your if/else statements are well defined for different array situations, like checking an array is empty vs not existing. In this case, the code should be like -
@if($model->restaurantmenue()->exists())
@foreach($restaurantmenue as $daily)
@foreach($daily->articles as $menue)
@if(!empty($menue->title))
<div class="card card-horizontal">
...
@else
No Articles for Today
@endif
@endforeach
@endforeach
@else
// Display default content or message if no articles are available
@endif
4. Incorrect looping structure: Adjust your loops to match the array structure and ensure you're iterating through each element correctly, as in this case checking for `$daily->articles` instead of directly accessing `$restaurantmenue`.