Book Image

Laravel 5 Essentials

By : Martin Bean
Book Image

Laravel 5 Essentials

By: Martin Bean

Overview of this book

Table of Contents (15 chapters)
Laravel 5 Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Collections


Historically, other frameworks that have shipped with their own ORMs and query builders have returned result sets as either multidimensional arrays or Plain Old PHP Objects (POPOs). Eloquent has taken its cue from other, more mature ORMs and instead returns result sets as an instance of a collection object.

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...