What are collections in laravel

The collection object is powerful as it not only contains the data returned from the database, but also many helper methods, allowing you to manipulate that data before displaying it to the user.

Checking whether a key exists in a collection

If you need to find out whether a particular key exists in a collection, you can use the contains method:

$users = User::all();
if ($users->contains($userId))
{
  // Do something
}

When querying models, any relations are also returned as subcollections, allowing you to use the exact same methods on relations too:

$user = User::find(1);
if ($user->roles->contains($roleId))
{
  // Do something
}

By default, models return an instance of Illuminate\Database\Eloquent\Collection. However, this can be overridden to instead use a different class. This is handy if we wanted to add additional methods to collections.

Recommended :  Part 1 - A complete guide for wordpress Plugin Development

Say for a collection of roles and we want to determine if administrator is one of those roles. If we imagine the administrator role to have a primary key value of 1, we can create a new method, like this:

<?php namespace App;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
class RoleCollection extends EloquentCollection {
  public function containsAdmin()
  {
    return $this->contains(1);
  }
}

The second part is to then tell the Role model to use our new collection:

use App\RoleCollection;

class Role extends Model {
  public function newCollection(array $models = array())
  {
    return new RoleCollection($models);
  }
}

Instead of instantiating the default Eloquent collection, it will instead create a new instance of our RoleCollection class, filling it with the results from our query. This means that every time we request roles, we can use our new containsAdmin method:

$user = User::find(1);

if ($user->roles->containsAdmin())
{
  // Let user administrate something
}
else
{
 // User does not have administrator role
}

Eloquent collections also have a plethora of other helpful functions for allowing you to manipulate, filter, and iterate over items. You can view more information on these methods at http://laravel.com/docs/master/eloquent#collections

Recommended :  Automate Your Angularjs Development using gulp and grunt

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares