Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a Laravel Collection is empty?

I create a view by doing an eloquent query and then pass it over to Blade.

@if($contacts != null)
//display contacts
@else
You dont have contacts
@endif

However it always assume that $contacts has something even if the query gives me nothing.

I did dd($contacts) and get:

Collection {#247 ▼
  #items: []
}

How do I check if it is empty?

like image 730
prgrm Avatar asked Dec 21 '16 18:12

prgrm


People also ask

How do I know if a collection is empty?

Using isEmpty() method The standard solution to check if a Java Collection is empty is calling the isEmpty() method on the corresponding collection. It returns true if the collection contains no elements.

IS NOT NULL PHP laravel?

Check if not null: whereNotNull SELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


Video Answer


3 Answers

If it is a Eloquent Collection as it appears to be from your example you can use the isEmpty collection helper function;

@if(!$contacts->isEmpty())
//display contacts
@else
You dont have contacts
@endif

Collections Documentation

like image 167
gsueagle2008 Avatar answered Oct 19 '22 19:10

gsueagle2008


There are few ways:

if (!empty($contacts))

if (!contacts->isEmpty())

if (count($contacts) > 0)

if ($contacts->count() > 0)
like image 40
Alexey Mezenin Avatar answered Oct 19 '22 19:10

Alexey Mezenin


Your Eloquent query returns an array of result, so you can use count.

@if(count($contacts) > 0)
//Display contacts
@else
//No contacts
@endif
like image 5
Michel Avatar answered Oct 19 '22 20:10

Michel