DEV Community

Alisson Zampietro
Alisson Zampietro

Posted on • Updated on


Collections Laravel

Two years ago, i've started to work with Laravel. I've never had some previous experience with collections and neither eloquent, so, it's not a post about deep funcionalities, but some interesting parts that helps me to understant better how the engine works.


One of the aspects that most drew my attention in Laravel was the Collection object. One thing that bothers me about PHP array functions is the lack of patterns. In the example below you can see that both functions iterate the array, although the way that you implement the callback function and the params is different:

array_map($callback, $array);
array_filter($array, $callback);
Enter fullscreen mode Exit fullscreen mode

As you are using an object when working with Collections, you don't need to worry about the callback position, since your base array is already defined in Object,

$array = new Collection([1,2,3,4);
Enter fullscreen mode Exit fullscreen mode

It looks better.

But the main reason why i'm in love with Collection, is that the Query Builder return a Collection. Let's checkout using the example below.
We're not digging in about database connection or something else, let's focus only on Collections feature.


use Illuminate\Database\Eloquent\Model;

class User extends Model
     * The attributes that should be visible in results.
     * @var array
    protected $visible = [

$user = User::where('enabled', true)->get();
Enter fullscreen mode Exit fullscreen mode

Now $user variable is ready to use collections methods, because the ->get() calling returns a collection.

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<