Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: find out if variable is collection

I want to find out if a variable is a collection.

I can't use is_object() because it will be true even if it is not an collection. For now I use this, and it works:

if(is_object($images) && get_class($images) != 'Illuminate\Database\Eloquent\Collection') { 

But I think it's so ugly that I spend time asking you about another solution.

Do you have any idea?

like image 431
Albert Avatar asked Jan 05 '16 18:01

Albert


People also ask

How do I check if an item is in collection in laravel?

You can use the contains() method in Laravel for Check some specific key of value exists or not. If value available in the collection for the specific key then returns true.

What is collection in laravel?

Laravel collection is a useful feature of the Laravel framework. A collection works like a PHP array, but it is more convenient. The collection class is located in the Illuminate\Support\Collection location. A collection allows you to create a chain of methods to map or reduce arrays.

What is pluck in laravel?

Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.

What is first () in laravel?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.


1 Answers

Couldn't you use

if(is_a($images, 'Illuminate\Database\Eloquent\Collection')) {     ....do whatever for a collection.... } else {     ....do whatever for not a collection.... } 

Or

if ($images instanceof \Illuminate\Database\Eloquent\Collection) {  } 
like image 137
P. Gearman Avatar answered Sep 29 '22 22:09

P. Gearman