I\'m learning Laravel and it uses OOPS concepts. Now I\'m finding it hard to understand the real difference between array and objects. I actually know what an array and obje
Actually the Collection class is a wrapper object which returns a collection of objects. For example, if you have a Model for example, User then you may use it in various ways, to get all records you may use User::all() and to get a single record you may use User::find(1) and there are other ways as well.
If you use all(), get() methods then you'll get a collection object, it means a collection of User models when you use these methods on User model and remember all() and get() always returns a collection of models even if there is only one model in it, so check this examaple:
$users = User::all(); // returns a collection
You may use first() method of Collection object like this:
$users = User::all();
$users->first();
Or directly just:
$user = User::first();
You may also use last to get the last item/model from the collection. You may also use get() like this:
$users = User::all();
$users = User::get(0) // to get first item/model
$users = User::get(1) // to get second item/model
You may also use a loop like this:
$users = User::get(); // same as all
// pass the collection to the view
return View::make('users.index')->with('users', $users);
Now in your views/users/index.blade.php view you may use a loop like this:
@foreach($users as $user)
{{ $user->username }}
{{ $user->email }}
@endforeach
It's important to knoe that, all() and get() methods returns a collection and first() and find(id) returns a single model object, so if you have a single model then you may directly use it like this:
$user = user::find(1); // 1 is id for example
return View::make('users.index')->with('user', $user);
In your view you may use:
{{ $user->email }}
You may use an object using -> for example $user->name and an array using $user['name'] but in this case you may use both syntax because Laravel's Eloquent/Model implements ArrayAccess (along with others) interface so every model that extends Eloquent could be used using both array and object syntax to access properties. So, following is possible:
$user = User::where('username', 'me')->get();
return View::make('users.index')->with('user', $user);
In the view you may use:
{{ $user->name }}
{{ $user['name'] }}
For better understanding of the Collection class and it's methods check the source code, you may find it at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Collection.php of your local installation and it extends Illuminate/Support/Collection.php class. Check both classes. You may also read this article, it'll help you more.