Laravel Check if Array is empty
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
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
php
@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
@endforeachThe Correct Syntax and Best Practices
1. Check array emptiness with Laravel's built-in `count` method:php
@if(count($array))
// Array is not empty, perform actions
@else
// Array is empty, display alternate content
@endifphp
@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)
@endifphp
@if(count(array_count_values($array)) == 0)
// Array is empty
@else
// Array has elements
@endifphp
@if($model->restaurantmenue()->exists())
// Relationship exists
@else
// No related records found
@endifCommon Mistakes and Solutions
1. Incorrect syntax: Ensure you use the proper control flow constructs, such as `if` statements, to check your conditions correctly.php
@if(count($array))
// Array is not empty
@else
// Array is empty
@endifphp
@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