Eloquent ORM

Introduction

The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding "Model" which is used to interact with that table.

Before getting started, be sure to configure a database connection in app/config/database.php.

Basic Usage

To get started, create an Eloquent model. Models typically live in the app/models directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file.

Defining An Eloquent Model

  1. class User extends Eloquent {}

Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a table property on your model:

  1. class User extends Eloquent {
  2. protected $table = 'my_users';
  3. }

Note: Eloquent will also assume that each table has a primary key column named id. You may define a primaryKey property to override this convention. Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.

Once a model is defined, you are ready to start retrieving and creating records in your table. Note that you will need to place updated_at and created_at columns on your table by default. If you do not wish to have these columns automatically maintained, set the $timestamps property on your model to false.

Retrieving All Models

  1. $users = User::all();

Retrieving A Record By Primary Key

  1. $user = User::find(1);
  2. var_dump($user->name);

Note: All methods available on the query builder are also available when querying Eloquent models.

Retrieving A Model By Primary Key Or Throw An Exception

Sometimes you may wish to throw an exception if a model is not found, allowing you to catch the exceptions using an App::error handler and display a 404 page.

  1. $model = User::findOrFail(1);
  2. $model = User::where('votes', '>', 100)->firstOrFail();

To register the error handler, listen for the ModelNotFoundException

  1. use Illuminate\Database\Eloquent\ModelNotFoundException;
  2. App::error(function(ModelNotFoundException $e)
  3. {
  4. return Response::make('Not Found', 404);
  5. });

Querying Using Eloquent Models

  1. $users = User::where('votes', '>', 100)->take(10)->get();
  2. foreach ($users as $user)
  3. {
  4. var_dump($user->name);
  5. }

Eloquent Aggregates

Of course, you may also use the query builder aggregate functions.

  1. $count = User::where('votes', '>', 100)->count();

If you are unable to generate the query you need via the fluent interface, feel free to use whereRaw:

  1. $users = User::whereRaw('age > ? and votes = 100', array(25))->get();

Chunking Results

If you need to process a lot (thousands) of Eloquent records, using the chunk command will allow you to do without eating all of your RAM:

  1. User::chunk(200, function($users)
  2. {
  3. foreach ($users as $user)
  4. {
  5. //
  6. }
  7. });

The first argument passed to the method is the number of records you wish to receive per "chunk". The Closure passed as the second argument will be called for each chunk that is pulled from the database.

Specifying The Query Connection

You may also specify which database connection should be used when running an Eloquent query. Simply use the on method:

  1. $user = User::on('connection-name')->find(1);

Mass Assignment

When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment. This is convenient; however, can be a serious security concern when blindly passing user input into a model. If user input is blindly passed into a model, the user is free to modify any and all of the model's attributes. For this reason, all Eloquent models protect against mass-assignment by default.

To get started, set the fillable or guarded properties on your model.

Defining Fillable Attributes On A Model

The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level.

  1. class User extends Eloquent {
  2. protected $fillable = array('first_name', 'last_name', 'email');
  3. }

In this example, only the three listed attributes will be mass-assignable.

Defining Guarded Attributes On A Model

The inverse of fillable is guarded, and serves as a "black-list" instead of a "white-list":

  1. class User extends Eloquent {
  2. protected $guarded = array('id', 'password');
  3. }

Note: When using guarded, you should still never pass Input::get() or any raw array of user controlled input into a save or update method, as any column that is not guarded may be updated.

Blocking All Attributes From Mass Assignment

In the example above, the id and password attributes may not be mass assigned. All other attributes will be mass assignable. You may also block all attributes from mass assignment using the guard property:

  1. protected $guarded = array('*');

Insert, Update, Delete

To create a new record in the database from a model, simply create a new model instance and call the save method.

Saving A New Model

  1. $user = new User;
  2. $user->name = 'John';
  3. $user->save();

Note: Typically, your Eloquent models will have auto-incrementing keys. However, if you wish to specify your own keys, set the incrementing property on your model to false.

You may also use the create method to save a new model in a single line. The inserted model instance will be returned to you from the method. However, before doing so, you will need to specify either a fillable or guarded attribute on the model, as all Eloquent models protect against mass-assignment.

After saving or creating a new model that uses auto-incrementing IDs, you may retrieve the ID by accessing the object's id attribute:

  1. $insertedId = $user->id;

Setting The Guarded Attributes On The Model

  1. class User extends Eloquent {
  2. protected $guarded = array('id', 'account_id');
  3. }

Using The Model Create Method

  1. // Create a new user in the database...
  2. $user = User::create(array('name' => 'John'));
  3. // Retrieve the user by the attributes, or create it if it doesn't exist...
  4. $user = User::firstOrCreate(array('name' => 'John'));
  5. // Retrieve the user by the attributes, or instantiate a new instance...
  6. $user = User::firstOrNew(array('name' => 'John'));

Updating A Retrieved Model

To update a model, you may retrieve it, change an attribute, and use the save method:

  1. $user = User::find(1);
  2. $user->email = '[email protected]';
  3. $user->save();

Saving A Model And Relationships

Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:

  1. $user->push();

You may also run updates as queries against a set of models:

  1. $affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));

Note: No model events are fired when updating a set of models via the Eloquent query builder.

Deleting An Existing Model

To delete a model, simply call the delete method on the instance:

  1. $user = User::find(1);
  2. $user->delete();

Deleting An Existing Model By Key

  1. User::destroy(1);
  2. User::destroy(array(1, 2, 3));
  3. User::destroy(1, 2, 3);

Of course, you may also run a delete query on a set of models:

  1. $affectedRows = User::where('votes', '>', 100)->delete();

Updating Only The Model's Timestamps

If you wish to simply update the timestamps on a model, you may use the touch method:

  1. $user->touch();

Soft Deleting

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, apply the SoftDeletingTrait to the model:

  1. use Illuminate\Database\Eloquent\SoftDeletingTrait;
  2. class User extends Eloquent {
  3. use SoftDeletingTrait;
  4. protected $dates = ['deleted_at'];
  5. }

To add a deleted_at column to your table, you may use the softDeletes method from a migration:

  1. $table->softDeletes();

Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.

Forcing Soft Deleted Models Into Results

To force soft deleted models to appear in a result set, use the withTrashed method on the query:

  1. $users = User::withTrashed()->where('account_id', 1)->get();

The withTrashed method may be used on a defined relationship:

  1. $user->posts()->withTrashed()->get();

If you wish to only receive soft deleted models in your results, you may use the onlyTrashed method:

  1. $users = User::onlyTrashed()->where('account_id', 1)->get();

To restore a soft deleted model into an active state, use the restore method:

  1. $user->restore();

You may also use the restore method on a query:

  1. User::withTrashed()->where('account_id', 1)->restore();

Like with withTrashed, the restore method may also be used on relationships:

  1. $user->posts()->restore();

If you wish to truly remove a model from the database, you may use the forceDelete method:

  1. $user->forceDelete();

The forceDelete method also works on relationships:

  1. $user->posts()->forceDelete();

To determine if a given model instance has been soft deleted, you may use the trashed method:

  1. if ($user->trashed())
  2. {
  3. //
  4. }

Timestamps

By default, Eloquent will maintain the created_at and updated_at columns on your database table automatically. Simply add these timestamp columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model:

Disabling Auto Timestamps

  1. class User extends Eloquent {
  2. protected $table = 'users';
  3. public $timestamps = false;
  4. }

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

  1. class User extends Eloquent {
  2. protected function getDateFormat()
  3. {
  4. return 'U';
  5. }
  6. }

Query Scopes

Defining A Query Scope

Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:

  1. class User extends Eloquent {
  2. public function scopePopular($query)
  3. {
  4. return $query->where('votes', '>', 100);
  5. }
  6. public function scopeWomen($query)
  7. {
  8. return $query->whereGender('W');
  9. }
  10. }

Utilizing A Query Scope

  1. $users = User::popular()->women()->orderBy('created_at')->get();

Dynamic Scopes

Sometimes you may wish to define a scope that accepts parameters. Just add your parameters to your scope function:

  1. class User extends Eloquent {
  2. public function scopeOfType($query, $type)
  3. {
  4. return $query->whereType($type);
  5. }
  6. }

Then pass the parameter into the scope call:

  1. $users = User::ofType('member')->get();

Global Scopes

Sometimes you may wish to define a scope that applies to all queries performed on a model. In essence, this is how Eloquent's own "soft delete" feature works. Global scopes are defined using a combination of PHP traits and an implementation of Illuminate\Database\Eloquent\ScopeInterface.

First, let's define a trait. For this example, we'll use the SoftDeletingTrait that ships with Laravel:

  1. trait SoftDeletingTrait {
  2. /**
  3. * Boot the soft deleting trait for a model.
  4. *
  5. * @return void
  6. */
  7. public static function bootSoftDeletingTrait()
  8. {
  9. static::addGlobalScope(new SoftDeletingScope);
  10. }
  11. }

If an Eloquent model uses a trait that has a method matching the bootNameOfTrait naming convention, that trait method will be called when the Eloquent model is booted, giving you an opportunity to register a global scope, or do anything else you want. A scope must implement ScopeInterface, which specifies two methods: apply and remove.

The apply method receives an Illuminate\Database\Eloquent\Builder query builder object, and is responsible for adding any additional where clauses that the scope wishes to add. The remove method also receives a Builder object and is responsible for reversing the action taken by apply. In other words, remove should remove the where clause (or any other clause) that was added. So, for our SoftDeletingScope, the methods look something like this:

  1. /**
  2. * Apply the scope to a given Eloquent query builder.
  3. *
  4. * @param \Illuminate\Database\Eloquent\Builder $builder
  5. * @return void
  6. */
  7. public function apply(Builder $builder)
  8. {
  9. $model = $builder->getModel();
  10. $builder->whereNull($model->getQualifiedDeletedAtColumn());
  11. }
  12. /**
  13. * Remove the scope from the given Eloquent query builder.
  14. *
  15. * @param \Illuminate\Database\Eloquent\Builder $builder
  16. * @return void
  17. */
  18. public function remove(Builder $builder)
  19. {
  20. $column = $builder->getModel()->getQualifiedDeletedAtColumn();
  21. $query = $builder->getQuery();
  22. foreach ((array) $query->wheres as $key => $where)
  23. {
  24. // If the where clause is a soft delete date constraint, we will remove it from
  25. // the query and reset the keys on the wheres. This allows this developer to
  26. // include deleted model in a relationship result set that is lazy loaded.
  27. if ($this->isSoftDeleteConstraint($where, $column))
  28. {
  29. unset($query->wheres[$key]);
  30. $query->wheres = array_values($query->wheres);
  31. }
  32. }
  33. }

Relationships

Of course, your database tables are probably related to one another. For example, a blog post may have many comments, or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy. Laravel supports many types of relationships:

One To One

Defining A One To One Relation

A one-to-one relationship is a very basic relation. For example, a User model might have one Phone. We can define this relation in Eloquent:

  1. class User extends Eloquent {
  2. public function phone()
  3. {
  4. return $this->hasOne('Phone');
  5. }
  6. }

The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve it using Eloquent's dynamic properties:

  1. $phone = User::find(1)->phone;

The SQL performed by this statement will be as follows:

  1. select * from users where id = 1
  2. select * from phones where user_id = 1

Take note that Eloquent assumes the foreign key of the relationship based on the model name. In this case, Phone model is assumed to use a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method. Furthermore, you may pass a third argument to the method to specify which local column that should be used for the association:

  1. return $this->hasOne('Phone', 'foreign_key');
  2. return $this->hasOne('Phone', 'foreign_key', 'local_key');

Defining The Inverse Of A Relation

To define the inverse of the relationship on the Phone model, we use the belongsTo method:

  1. class Phone extends Eloquent {
  2. public function user()
  3. {
  4. return $this->belongsTo('User');
  5. }
  6. }

In the example above, Eloquent will look for a user_id column on the phones table. If you would like to define a different foreign key column, you may pass it as the second argument to the belongsTo method:

  1. class Phone extends Eloquent {
  2. public function user()
  3. {
  4. return $this->belongsTo('User', 'local_key');
  5. }
  6. }

Additionally, you pass a third parameter which specifies the name of the associated column on the parent table:

  1. class Phone extends Eloquent {
  2. public function user()
  3. {
  4. return $this->belongsTo('User', 'local_key', 'parent_key');
  5. }
  6. }

One To Many

An example of a one-to-many relation is a blog post that "has many" comments. We can model this relation like so:

  1. class Post extends Eloquent {
  2. public function comments()
  3. {
  4. return $this->hasMany('Comment');
  5. }
  6. }

Now we can access the post's comments through the dynamic property:

  1. $comments = Post::find(1)->comments;

If you need to add further constraints to which comments are retrieved, you may call the comments method and continue chaining conditions:

  1. $comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

Again, you may override the conventional foreign key by passing a second argument to the hasMany method. And, like the hasOne relation, the local column may also be specified:

  1. return $this->hasMany('Comment', 'foreign_key');
  2. return $this->hasMany('Comment', 'foreign_key', 'local_key');

Defining The Inverse Of A Relation

To define the inverse of the relationship on the Comment model, we use the belongsTo method:

  1. class Comment extends Eloquent {
  2. public function post()
  3. {
  4. return $this->belongsTo('Post');
  5. }
  6. }

Many To Many

Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and should have user_id and role_id columns.

We can define a many-to-many relation using the belongsToMany method:

  1. class User extends Eloquent {
  2. public function roles()
  3. {
  4. return $this->belongsToMany('Role');
  5. }
  6. }

Now, we can retrieve the roles through the User model:

  1. $roles = User::find(1)->roles;

If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the belongsToMany method:

  1. return $this->belongsToMany('Role', 'user_roles');

You may also override the conventional associated keys:

  1. return $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');

Of course, you may also define the inverse of the relationship on the Role model:

  1. class Role extends Eloquent {
  2. public function users()
  3. {
  4. return $this->belongsToMany('User');
  5. }
  6. }

Has Many Through

The "has many through" relation provides a convenient short-cut for accessing distant relations via an intermediate relation. For example, a Country model might have many Post through a User model. The tables for this relationship would look like this:

  1. countries
  2. id - integer
  3. name - string
  4. users
  5. id - integer
  6. country_id - integer
  7. name - string
  8. posts
  9. id - integer
  10. user_id - integer
  11. title - string

Even though the posts table does not contain a country_id column, the hasManyThrough relation will allow us to access a country's posts via $country->posts. Let's define the relationship:

  1. class Country extends Eloquent {
  2. public function posts()
  3. {
  4. return $this->hasManyThrough('Post', 'User');
  5. }
  6. }

If you would like to manually specify the keys of the relationship, you may pass them as the third and fourth arguments to the method:

  1. class Country extends Eloquent {
  2. public function posts()
  3. {
  4. return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
  5. }
  6. }

Polymorphic Relations

Polymorphic relations allow a model to belong to more than one other model, on a single association. For example, you might have a photo model that belongs to either a staff model or an order model. We would define this relation like so:

  1. class Photo extends Eloquent {
  2. public function imageable()
  3. {
  4. return $this->morphTo();
  5. }
  6. }
  7. class Staff extends Eloquent {
  8. public function photos()
  9. {
  10. return $this->morphMany('Photo', 'imageable');
  11. }
  12. }
  13. class Order extends Eloquent {
  14. public function photos()
  15. {
  16. return $this->morphMany('Photo', 'imageable');
  17. }
  18. }

Retrieving A Polymorphic Relation

Now, we can retrieve the photos for either a staff member or an order:

  1. $staff = Staff::find(1);
  2. foreach ($staff->photos as $photo)
  3. {
  4. //
  5. }

Retrieving The Owner Of A Polymorphic Relation

However, the true "polymorphic" magic is when you access the staff or order from the Photo model:

  1. $photo = Photo::find(1);
  2. $imageable = $photo->imageable;

The imageable relation on the Photo model will return either a Staff or Order instance, depending on which type of model owns the photo.

Polymorphic Relation Table Structure

To help understand how this works, let's explore the database structure for a polymorphic relation:

  1. staff
  2. id - integer
  3. name - string
  4. orders
  5. id - integer
  6. price - integer
  7. photos
  8. id - integer
  9. path - string
  10. imageable_id - integer
  11. imageable_type - string

The key fields to notice here are the imageable_id and imageable_type on the photos table. The ID will contain the ID value of, in this example, the owning staff or order, while the type will contain the class name of the owning model. This is what allows the ORM to determine which type of owning model to return when accessing the imageable relation.

Many To Many Polymorphic Relations

Polymorphic Many To Many Relation Table Structure

In addition to traditional polymorphic relations, you may also specify many-to-many polymorphic relations. For example, a blog Post and Video model could share a polymorphic relation to a Tag model. First, let's examine the table structure:

  1. posts
  2. id - integer
  3. name - string
  4. videos
  5. id - integer
  6. name - string
  7. tags
  8. id - integer
  9. name - string
  10. taggables
  11. tag_id - integer
  12. taggable_id - integer
  13. taggable_type - string

Next, we're ready to setup the relationships on the model. The Post and Video model will both have a morphToMany relationship via a tags method:

  1. class Post extends Eloquent {
  2. public function tags()
  3. {
  4. return $this->morphToMany('Tag', 'taggable');
  5. }
  6. }

The Tag model may define a method for each of its relationships:

  1. class Tag extends Eloquent {
  2. public function posts()
  3. {
  4. return $this->morphedByMany('Post', 'taggable');
  5. }
  6. public function videos()
  7. {
  8. return $this->morphedByMany('Video', 'taggable');
  9. }
  10. }

Querying Relations

Querying Relations When Selecting

When accessing the records for a model, you may wish to limit your results based on the existence of a relationship. For example, you wish to pull all blog posts that have at least one comment. To do so, you may use the has method:

  1. $posts = Post::has('comments')->get();

You may also specify an operator and a count:

  1. $posts = Post::has('comments', '>=', 3)->get();

If you need even more power, you may use the whereHas and orWhereHas methods to put "where" conditions on your has queries:

  1. $posts = Post::whereHas('comments', function($q)
  2. {
  3. $q->where('content', 'like', 'foo%');
  4. })->get();

Dynamic Properties

Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation. For example, with the following model $phone:

  1. class Phone extends Eloquent {
  2. public function user()
  3. {
  4. return $this->belongsTo('User');
  5. }
  6. }
  7. $phone = Phone::find(1);

Instead of echoing the user's email like this:

  1. echo $phone->user()->first()->email;

It may be shortened to simply:

  1. echo $phone->user->email;

Note: Relationships that return many results will return an instance of the Illuminate\Database\Eloquent\Collection class.

Eager Loading

Eager loading exists to alleviate the N + 1 query problem. For example, consider a Book model that is related to Author. The relationship is defined like so:

  1. class Book extends Eloquent {
  2. public function author()
  3. {
  4. return $this->belongsTo('Author');
  5. }
  6. }

Now, consider the following code:

  1. foreach (Book::all() as $book)
  2. {
  3. echo $book->author->name;
  4. }

This loop will execute 1 query to retrieve all of the books on the table, then another query for each book to retrieve the author. So, if we have 25 books, this loop would run 26 queries.

Thankfully, we can use eager loading to drastically reduce the number of queries. The relationships that should be eager loaded may be specified via the with method:

  1. foreach (Book::with('author')->get() as $book)
  2. {
  3. echo $book->author->name;
  4. }

In the loop above, only two queries will be executed:

  1. select * from books
  2. select * from authors where id in (1, 2, 3, 4, 5, ...)

Wise use of eager loading can drastically increase the performance of your application.

Of course, you may eager load multiple relationships at one time:

  1. $books = Book::with('author', 'publisher')->get();

You may even eager load nested relationships:

  1. $books = Book::with('author.contacts')->get();

In the example above, the author relationship will be eager loaded, and the author's contacts relation will also be loaded.

Eager Load Constraints

Sometimes you may wish to eager load a relationship, but also specify a condition for the eager load. Here's an example:

  1. $users = User::with(array('posts' => function($query)
  2. {
  3. $query->where('title', 'like', '%first%');
  4. }))->get();

In this example, we're eager loading the user's posts, but only if the post's title column contains the word "first".

Of course, eager loading Closures aren't limited to "constraints". You may also apply orders:

  1. $users = User::with(array('posts' => function($query)
  2. {
  3. $query->orderBy('created_at', 'desc');
  4. }))->get();

Lazy Eager Loading

It is also possible to eagerly load related models directly from an already existing model collection. This may be useful when dynamically deciding whether to load related models or not, or in combination with caching.

  1. $books = Book::all();
  2. $books->load('author', 'publisher');

You will often need to insert new related models. For example, you may wish to insert a new comment for a post. Instead of manually setting the post_id foreign key on the model, you may insert the new comment from its parent Post model directly:

  1. $comment = new Comment(array('message' => 'A new comment.'));
  2. $post = Post::find(1);
  3. $comment = $post->comments()->save($comment);

In this example, the post_id field will automatically be set on the inserted comment.

If you need to save multiple related models:

  1. $comments = array(
  2. new Comment(array('message' => 'A new comment.')),
  3. new Comment(array('message' => 'Another comment.')),
  4. new Comment(array('message' => 'The latest comment.'))
  5. );
  6. $post = Post::find(1);
  7. $post->comments()->saveMany($comments);

Associating Models (Belongs To)

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model:

  1. $account = Account::find(10);
  2. $user->account()->associate($account);
  3. $user->save();

You may also insert related models when working with many-to-many relations. Let's continue using our User and Role models as examples. We can easily attach new roles to a user using the attach method:

Attaching Many To Many Models

  1. $user = User::find(1);
  2. $user->roles()->attach(1);

You may also pass an array of attributes that should be stored on the pivot table for the relation:

  1. $user->roles()->attach(1, array('expires' => $expires));

Of course, the opposite of attach is detach:

  1. $user->roles()->detach(1);

Both attach and detach also take arrays of IDs as input:

  1. $user = User::find(1);
  2. $user->roles()->detach([1, 2, 3]);
  3. $user->roles()->attach([1 => ['attribute1' => 'value1'], 2, 3]);

Using Sync To Attach Many To Many Models

You may also use the sync method to attach related models. The sync method accepts an array of IDs to place on the pivot table. After this operation is complete, only the IDs in the array will be on the intermediate table for the model:

  1. $user->roles()->sync(array(1, 2, 3));

Adding Pivot Data When Syncing

You may also associate other pivot table values with the given IDs:

  1. $user->roles()->sync(array(1 => array('expires' => true)));

Sometimes you may wish to create a new related model and attach it in a single command. For this operation, you may use the save method:

  1. $role = new Role(array('name' => 'Editor'));
  2. User::find(1)->roles()->save($role);

In this example, the new Role model will be saved and attached to the user model. You may also pass an array of attributes to place on the joining table for this operation:

  1. User::find(1)->roles()->save($role, array('expires' => $expires));

Touching Parent Timestamps

When a model belongsTo another model, such as a Comment which belongs to a Post, it is often helpful to update the parent's timestamp when the child model is updated. For example, when a Comment model is updated, you may want to automatically touch the updated_at timestamp of the owning Post. Eloquent makes it easy. Just add a touches property containing the names of the relationships to the child model:

  1. class Comment extends Eloquent {
  2. protected $touches = array('post');
  3. public function post()
  4. {
  5. return $this->belongsTo('Post');
  6. }
  7. }

Now, when you update a Comment, the owning Post will have its updated_at column updated:

  1. $comment = Comment::find(1);
  2. $comment->text = 'Edit to this comment!';
  3. $comment->save();

Working With Pivot Tables

As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User object has many Role objects that it is related to. After accessing this relationship, we may access the pivot table on the models:

  1. $user = User::find(1);
  2. foreach ($user->roles as $role)
  3. {
  4. echo $role->pivot->created_at;
  5. }

Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used as any other Eloquent model.

By default, only the keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

  1. return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Now the foo and bar attributes will be accessible on our pivot object for the Role model.

If you want your pivot table to have automatically maintained created_at and updated_at timestamps, use the withTimestamps method on the relationship definition:

  1. return $this->belongsToMany('Role')->withTimestamps();

Deleting Records On A Pivot Table

To delete all records on the pivot table for a model, you may use the detach method:

  1. User::find(1)->roles()->detach();

Note that this operation does not delete records from the roles table, but only from the pivot table.

Updating A Record On A Pivot Table

Sometimes you may need to update your pivot table, but not detach it. If you wish to update your pivot table in place you may use updateExistingPivot method like so:

  1. User::find(1)->roles()->updateExistingPivot($roleId, $attributes);

Defining A Custom Pivot Model

Laravel also allows you to define a custom Pivot model. To define a custom model, first create your own "Base" model class that extends Eloquent. In your other Eloquent models, extend this custom base model instead of the default Eloquent base. In your base model, add the following function that returns an instance of your custom Pivot model:

  1. public function newPivot(Model $parent, array $attributes, $table, $exists)
  2. {
  3. return new YourCustomPivot($parent, $attributes, $table, $exists);
  4. }

Collections

All multi-result sets returned by Eloquent, either via the get method or a relationship, will return a collection object. This object implements the IteratorAggregate PHP interface so it can be iterated over like an array. However, this object also has a variety of other helpful methods for working with result sets.

Checking If A Collection Contains A Key

For example, we may determine if a result set contains a given primary key using the contains method:

  1. $roles = User::find(1)->roles;
  2. if ($roles->contains(2))
  3. {
  4. //
  5. }

Collections may also be converted to an array or JSON:

  1. $roles = User::find(1)->roles->toArray();
  2. $roles = User::find(1)->roles->toJson();

If a collection is cast to a string, it will be returned as JSON:

  1. $roles = (string) User::find(1)->roles;

Iterating Collections

Eloquent collections also contain a few helpful methods for looping and filtering the items they contain:

  1. $roles = $user->roles->each(function($role)
  2. {
  3. //
  4. });

Filtering Collections

When filtering collections, the callback provided will be used as callback for array_filter.

  1. $users = $users->filter(function($user)
  2. {
  3. return $user->isAdmin();
  4. });

Note: When filtering a collection and converting it to JSON, try calling the values function first to reset the array's keys.

Applying A Callback To Each Collection Object

  1. $roles = User::find(1)->roles;
  2. $roles->each(function($role)
  3. {
  4. //
  5. });

Sorting A Collection By A Value

  1. $roles = $roles->sortBy(function($role)
  2. {
  3. return $role->created_at;
  4. });

Sorting A Collection By A Value

  1. $roles = $roles->sortBy('created_at');

Returning A Custom Collection Type

Sometimes, you may wish to return a custom Collection object with your own added methods. You may specify this on your Eloquent model by overriding the newCollection method:

  1. class User extends Eloquent {
  2. public function newCollection(array $models = array())
  3. {
  4. return new CustomCollection($models);
  5. }
  6. }

Accessors & Mutators

Defining An Accessor

Eloquent provides a convenient way to transform your model attributes when getting or setting them. Simply define a getFooAttribute method on your model to declare an accessor. Keep in mind that the methods should follow camel-casing, even though your database columns are snake-case:

  1. class User extends Eloquent {
  2. public function getFirstNameAttribute($value)
  3. {
  4. return ucfirst($value);
  5. }
  6. }

In the example above, the first_name column has an accessor. Note that the value of the attribute is passed to the accessor.

Defining A Mutator

Mutators are declared in a similar fashion:

  1. class User extends Eloquent {
  2. public function setFirstNameAttribute($value)
  3. {
  4. $this->attributes['first_name'] = strtolower($value);
  5. }
  6. }

Date Mutators

By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class.

You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the getDates method of the model:

  1. public function getDates()
  2. {
  3. return array('created_at');
  4. }

When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d), date-time string, and of course a DateTime / Carbon instance.

To totally disable date mutations, simply return an empty array from the getDates method:

  1. public function getDates()
  2. {
  3. return array();
  4. }

Model Events

Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored.

Whenever a new item is saved for the first time, the creating and created events will fire. If an item is not new and the save method is called, the updating / updated events will fire. In both cases, the saving / saved events will fire.

Cancelling Save Operations Via Events

If false is returned from the creating, updating, saving, or deleting events, the action will be cancelled:

  1. User::creating(function($user)
  2. {
  3. if ( ! $user->isValid()) return false;
  4. });

Setting A Model Boot Method

Eloquent models also contain a static boot method, which may provide a convenient place to register your event bindings.

  1. class User extends Eloquent {
  2. public static function boot()
  3. {
  4. parent::boot();
  5. // Setup event bindings...
  6. }
  7. }

Model Observers

To consolidate the handling of model events, you may register a model observer. An observer class may have methods that correspond to the various model events. For example, creating, updating, saving methods may be on an observer, in addition to any other model event name.

So, for example, a model observer might look like this:

  1. class UserObserver {
  2. public function saving($model)
  3. {
  4. //
  5. }
  6. public function saved($model)
  7. {
  8. //
  9. }
  10. }

You may register an observer instance using the observe method:

  1. User::observe(new UserObserver);

Converting To Arrays / JSON

Converting A Model To An Array

When building JSON APIs, you may often need to convert your models and relationships to arrays or JSON. So, Eloquent includes methods for doing so. To convert a model and its loaded relationship to an array, you may use the toArray method:

  1. $user = User::with('roles')->first();
  2. return $user->toArray();

Note that entire collections of models may also be converted to arrays:

  1. return User::all()->toArray();

Converting A Model To JSON

To convert a model to JSON, you may use the toJson method:

  1. return User::find(1)->toJson();

Returning A Model From A Route

Note that when a model or collection is cast to a string, it will be converted to JSON, meaning you can return Eloquent objects directly from your application's routes!

  1. Route::get('users', function()
  2. {
  3. return User::all();
  4. });

Hiding Attributes From Array Or JSON Conversion

Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a hidden property definition to your model:

  1. class User extends Eloquent {
  2. protected $hidden = array('password');
  3. }

Note: When hiding relationships, use the relationship's method name, not the dynamic accessor name.

Alternatively, you may use the visible property to define a white-list:

  1. protected $visible = array('first_name', 'last_name');

Occasionally, you may need to add array attributes that do not have a corresponding column in your database. To do so, simply define an accessor for the value:

  1. public function getIsAdminAttribute()
  2. {
  3. return $this->attributes['admin'] == 'yes';
  4. }

Once you have created the accessor, just add the value to the appends property on the model:

  1. protected $appends = array('is_admin');

Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms. Attributes in the appends array respect the visible and hidden configuration on the model.