Eloquent: Getting Started

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. Models allow you to query for data in your tables, as well as insert new records into the table.

Before getting started, be sure to configure a database connection in config/database.php. For more information on configuring your database, check out the documentation.

Defining Models

To get started, let's create an Eloquent model. Models typically live in the app directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file. All Eloquent models extend Illuminate\Database\Eloquent\Model class.

The easiest way to create a model instance is using the make:model Artisan command:

  1. php artisan make:model User

If you would like to generate a database migration when you generate the model, you may use the —migration or -m option:

  1. php artisan make:model User --migration
  2. php artisan make:model User -m

Eloquent Model Conventions

Now, let's look at an example Flight model, which we will use to retrieve and store information from our flights database table:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. //
  7. }

Table Names

Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake 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 Flight model stores records in the flights table. You may specify a custom table by defining a table property on your model:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * The table associated with the model.
  8. *
  9. * @var string
  10. */
  11. protected $table = 'my_flights';
  12. }

Primary Keys

Eloquent will also assume that each table has a primary key column named id. You may define a $primaryKey property to override this convention.

In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.

Timestamps

By default, Eloquent expects created_at and updated_at columns to exist on your tables. If you do not wish to have these columns automatically managed by Eloquent, set the $timestamps property on your model to false:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * Indicates if the model should be timestamped.
  8. *
  9. * @var bool
  10. */
  11. public $timestamps = false;
  12. }

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * The storage format of the model's date columns.
  8. *
  9. * @var string
  10. */
  11. protected $dateFormat = 'U';
  12. }

If you need to customize the names of the columns used to store the timestamps, you may set the CREATED_AT and UPDATED_AT constants in your model:

  1. <?php
  2. class Flight extends Model
  3. {
  4. const CREATED_AT = 'creation_date';
  5. const UPDATED_AT = 'last_update';
  6. }

Database Connection

By default, all Eloquent models will use the default database connection configured for your application. If you would like to specify a different connection for the model, use the $connection property:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * The connection name for the model.
  8. *
  9. * @var string
  10. */
  11. protected $connection = 'connection-name';
  12. }

Retrieving Models

Once you have created a model and its associated database table, you are ready to start retrieving data from your database. Think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:

  1. <?php
  2. use App\Flight;
  3. $flights = App\Flight::all();
  4. foreach ($flights as $flight) {
  5. echo $flight->name;
  6. }

Adding Additional Constraints

The Eloquent all method will return all of the results in the model's table. Since each Eloquent model serves as a query builder, you may also add constraints to queries, and then use the get method to retrieve the results:

  1. $flights = App\Flight::where('active', 1)
  2. ->orderBy('name', 'desc')
  3. ->take(10)
  4. ->get();

{tip} Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries.

Collections

For Eloquent methods like all and get which retrieve multiple results, an instance of Illuminate\Database\Eloquent\Collection will be returned. The Collection class provides a variety of helpful methods for working with your Eloquent results:

  1. $flights = $flights->reject(function ($flight) {
  2. return $flight->cancelled;
  3. });

Of course, you may also simply loop over the collection like an array:

  1. foreach ($flights as $flight) {
  2. echo $flight->name;
  3. }

Chunking Results

If you need to process thousands of Eloquent records, use the chunk command. The chunk method will retrieve a "chunk" of Eloquent models, feeding them to a given Closure for processing. Using the chunk method will conserve memory when working with large result sets:

  1. Flight::chunk(200, function ($flights) {
  2. foreach ($flights as $flight) {
  3. //
  4. }
  5. });

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 retrieved from the database. A database query will be executed to retrieve each chunk of records passed to the Closure.

Using Cursors

The cursor method allows you to iterate through your database records using a cursor, which will only execute a single query. When processing large amounts of data, the cursor method may be used to greatly reduce your memory usage:

  1. foreach (Flight::where('foo', 'bar')->cursor() as $flight) {
  2. //
  3. }

Retrieving Single Models / Aggregates

Of course, in addition to retrieving all of the records for a given table, you may also retrieve single records using find and first. Instead of returning a collection of models, these methods return a single model instance:

  1. // Retrieve a model by its primary key...
  2. $flight = App\Flight::find(1);
  3. // Retrieve the first model matching the query constraints...
  4. $flight = App\Flight::where('active', 1)->first();

You may also call the find method with an array of primary keys, which will return a collection of the matching records:

  1. $flights = App\Flight::find([1, 2, 3]);

Not Found Exceptions

Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail and firstOrFail methods will retrieve the first result of the query; however, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException will be thrown:

  1. $model = App\Flight::findOrFail(1);
  2. $model = App\Flight::where('legs', '>', 100)->firstOrFail();

If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:

  1. Route::get('/api/flights/{id}', function ($id) {
  2. return App\Flight::findOrFail($id);
  3. });

Retrieving Aggregates

You may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:

  1. $count = App\Flight::where('active', 1)->count();
  2. $max = App\Flight::where('active', 1)->max('price');

Inserting & Updating Models

Inserts

To create a new record in the database, simply create a new model instance, set attributes on the model, then call the save method:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Flight;
  4. use Illuminate\Http\Request;
  5. use App\Http\Controllers\Controller;
  6. class FlightController extends Controller
  7. {
  8. /**
  9. * Create a new flight instance.
  10. *
  11. * @param Request $request
  12. * @return Response
  13. */
  14. public function store(Request $request)
  15. {
  16. // Validate the request...
  17. $flight = new Flight;
  18. $flight->name = $request->name;
  19. $flight->save();
  20. }
  21. }

In this example, we simply assign the name parameter from the incoming HTTP request to the name attribute of the App\Flight model instance. When we call the save method, a record will be inserted into the database. The created_at and updated_at timestamps will automatically be set when the save method is called, so there is no need to set them manually.

Updates

The save method may also be used to update models that already exist in the database. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. Again, the updated_at timestamp will automatically be updated, so there is no need to manually set its value:

  1. $flight = App\Flight::find(1);
  2. $flight->name = 'New Flight Name';
  3. $flight->save();

Mass Updates

Updates can also be performed against any number of models that match a given query. In this example, all flights that are active and have a destination of San Diego will be marked as delayed:

  1. App\Flight::where('active', 1)
  2. ->where('destination', 'San Diego')
  3. ->update(['delayed' => 1]);

The update method expects an array of column and value pairs representing the columns that should be updated.

{note} When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

Mass Assignment

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

A mass-assignment vulnerability occurs when a user passes an unexpected HTTP parameter through a request, and that parameter changes a column in your database you did not expect. For example, a malicious user might send an is_admin parameter through an HTTP request, which is then passed into your model's create method, allowing the user to escalate themselves to an administrator.

So, to get started, you should define which model attributes you want to make mass assignable. You may do this using the $fillable property on the model. For example, let's make the name attribute of our Flight model mass assignable:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * The attributes that are mass assignable.
  8. *
  9. * @var array
  10. */
  11. protected $fillable = ['name'];
  12. }

Once we have made the attributes mass assignable, we can use the create method to insert a new record in the database. The create method returns the saved model instance:

  1. $flight = App\Flight::create(['name' => 'Flight 10']);

If you already have a model instance, you may use the fill method to populate it with an array of attributes:

  1. $flight->fill(['name' => 'Flight 22']);

Guarding Attributes

While $fillable serves as a "white list" of attributes that should be mass assignable, you may also choose to use $guarded. The $guarded property should contain an array of attributes that you do not want to be mass assignable. All other attributes not in the array will be mass assignable. So, $guarded functions like a "black list". Of course, you should use either $fillable or $guarded - not both. In the example below, all attributes except for price will be mass assignable:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class Flight extends Model
  5. {
  6. /**
  7. * The attributes that aren't mass assignable.
  8. *
  9. * @var array
  10. */
  11. protected $guarded = ['price'];
  12. }

If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array:

  1. /**
  2. * The attributes that aren't mass assignable.
  3. *
  4. * @var array
  5. */
  6. protected $guarded = [];

Other Creation Methods

firstOrCreate/ firstOrNew

There are two other methods you may use to create models by mass assigning attributes: firstOrCreate and firstOrNew. The firstOrCreate method will attempt to locate a database record using the given column / value pairs. If the model can not be found in the database, a record will be inserted with the given attributes.

The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:

  1. // Retrieve the flight by the attributes, or create it if it doesn't exist...
  2. $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
  3. // Retrieve the flight by the attributes, or instantiate a new instance...
  4. $flight = App\Flight::firstOrNew(['name' => 'Flight 10']);

updateOrCreate

You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model, so there's no need to call save():

  1. // If there's a flight from Oakland to San Diego, set the price to $99.
  2. // If no matching model exists, create one.
  3. $flight = App\Flight::updateOrCreate(
  4. ['departure' => 'Oakland', 'destination' => 'San Diego'],
  5. ['price' => 99]
  6. );

Deleting Models

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

  1. $flight = App\Flight::find(1);
  2. $flight->delete();

Deleting An Existing Model By Key

In the example above, we are retrieving the model from the database before calling the delete method. However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the destroy method:

  1. App\Flight::destroy(1);
  2. App\Flight::destroy([1, 2, 3]);
  3. App\Flight::destroy(1, 2, 3);

Deleting Models By Query

Of course, you may also run a delete statement on a set of models. In this example, we will delete all flights that are marked as inactive. Like mass updates, mass deletes will not fire any model events for the models that are deleted:

  1. $deletedRows = App\Flight::where('active', 0)->delete();

{note} When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

Soft Deleting

In addition to actually removing records from your database, Eloquent can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted. To enable soft deletes for a model, use the Illuminate\Database\Eloquent\SoftDeletes trait on the model and add the deleted_at column to your $dates property:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\SoftDeletes;
  5. class Flight extends Model
  6. {
  7. use SoftDeletes;
  8. /**
  9. * The attributes that should be mutated to dates.
  10. *
  11. * @var array
  12. */
  13. protected $dates = ['deleted_at'];
  14. }

Of course, you should add the deleted_at column to your database table. The Laravel schema builder contains a helper method to create this column:

  1. Schema::table('flights', function ($table) {
  2. $table->softDeletes();
  3. });

Now, when you call the delete method on the model, the deleted_at column will be set to the current date and time. And, when querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

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

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

Querying Soft Deleted Models

Including Soft Deleted Models

As noted above, soft deleted models will automatically be excluded from query results. However, you may force soft deleted models to appear in a result set using the withTrashed method on the query:

  1. $flights = App\Flight::withTrashed()
  2. ->where('account_id', 1)
  3. ->get();

The withTrashed method may also be used on a relationship query:

  1. $flight->history()->withTrashed()->get();

Retrieving Only Soft Deleted Models

The onlyTrashed method will retrieve only soft deleted models:

  1. $flights = App\Flight::onlyTrashed()
  2. ->where('airline_id', 1)
  3. ->get();

Restoring Soft Deleted Models

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model into an active state, use the restore method on a model instance:

  1. $flight->restore();

You may also use the restore method in a query to quickly restore multiple models. Again, like other "mass" operations, this will not fire any model events for the models that are restored:

  1. App\Flight::withTrashed()
  2. ->where('airline_id', 1)
  3. ->restore();

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

  1. $flight->history()->restore();

Permanently Deleting Models

Sometimes you may need to truly remove a model from your database. To permanently remove a soft deleted model from the database, use the forceDelete method:

  1. // Force deleting a single model instance...
  2. $flight->forceDelete();
  3. // Force deleting all related models...
  4. $flight->history()->forceDelete();

Query Scopes

Global Scopes

Global scopes allow you to add constraints to all queries for a given model. Laravel's own soft delete functionality utilizes global scopes to only pull "non-deleted" models from the database. Writing your own global scopes can provide a convenient, easy way to make sure every query for a given model receives certain constraints.

Writing Global Scopes

Writing a global scope is simple. Define a class that implements the Illuminate\Database\Eloquent\Scope interface. This interface requires you to implement one method: apply. The apply method may add where constraints to the query as needed:

  1. <?php
  2. namespace App\Scopes;
  3. use Illuminate\Database\Eloquent\Scope;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Builder;
  6. class AgeScope implements Scope
  7. {
  8. /**
  9. * Apply the scope to a given Eloquent query builder.
  10. *
  11. * @param \Illuminate\Database\Eloquent\Builder $builder
  12. * @param \Illuminate\Database\Eloquent\Model $model
  13. * @return void
  14. */
  15. public function apply(Builder $builder, Model $model)
  16. {
  17. $builder->where('age', '>', 200);
  18. }
  19. }

{tip} There is not a predefined folder for scopes in a default Laravel application, so feel free to make your own Scopes folder within your Laravel application's app directory.

Applying Global Scopes

To assign a global scope to a model, you should override a given model's boot method and use the addGlobalScope method:

  1. <?php
  2. namespace App;
  3. use App\Scopes\AgeScope;
  4. use Illuminate\Database\Eloquent\Model;
  5. class User extends Model
  6. {
  7. /**
  8. * The "booting" method of the model.
  9. *
  10. * @return void
  11. */
  12. protected static function boot()
  13. {
  14. parent::boot();
  15. static::addGlobalScope(new AgeScope);
  16. }
  17. }

After adding the scope, a query to User::all() will produce the following SQL:

  1. select * from `users` where `age` > 200

Anonymous Global Scopes

Eloquent also allows you to define global scopes using Closures, which is particularly useful for simple scopes that do not warrant a separate class:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Builder;
  5. class User extends Model
  6. {
  7. /**
  8. * The "booting" method of the model.
  9. *
  10. * @return void
  11. */
  12. protected static function boot()
  13. {
  14. parent::boot();
  15. static::addGlobalScope('age', function (Builder $builder) {
  16. $builder->where('age', '>', 200);
  17. });
  18. }
  19. }

Removing Global Scopes

If you would like to remove a global scope for a given query, you may use the withoutGlobalScope method. The method accepts the class name of the global scope as its only argument:

  1. User::withoutGlobalScope(AgeScope::class)->get();

If you would like to remove several or even all of the global scopes, you may use the withoutGlobalScopes method:

  1. // Remove all of the global scopes...
  2. User::withoutGlobalScopes()->get();
  3. // Remove some of the global scopes...
  4. User::withoutGlobalScopes([
  5. FirstScope::class, SecondScope::class
  6. ])->get();

Local Scopes

Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, simply prefix an Eloquent model method with scope.

Scopes should always return a query builder instance:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6. /**
  7. * Scope a query to only include popular users.
  8. *
  9. * @param \Illuminate\Database\Eloquent\Builder $query
  10. * @return \Illuminate\Database\Eloquent\Builder
  11. */
  12. public function scopePopular($query)
  13. {
  14. return $query->where('votes', '>', 100);
  15. }
  16. /**
  17. * Scope a query to only include active users.
  18. *
  19. * @param \Illuminate\Database\Eloquent\Builder $query
  20. * @return \Illuminate\Database\Eloquent\Builder
  21. */
  22. public function scopeActive($query)
  23. {
  24. return $query->where('active', 1);
  25. }
  26. }

Utilizing A Local Scope

Once the scope has been defined, you may call the scope methods when querying the model. However, you do not need to include the scope prefix when calling the method. You can even chain calls to various scopes, for example:

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

Dynamic Scopes

Sometimes you may wish to define a scope that accepts parameters. To get started, just add your additional parameters to your scope. Scope parameters should be defined after the $query parameter:

  1. <?php
  2. namespace App;
  3. use Illuminate\Database\Eloquent\Model;
  4. class User extends Model
  5. {
  6. /**
  7. * Scope a query to only include users of a given type.
  8. *
  9. * @param \Illuminate\Database\Eloquent\Builder $query
  10. * @param mixed $type
  11. * @return \Illuminate\Database\Eloquent\Builder
  12. */
  13. public function scopeOfType($query, $type)
  14. {
  15. return $query->where('type', $type);
  16. }
  17. }

Now, you may pass the parameters when calling the scope:

  1. $users = App\User::ofType('admin')->get();

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. Events allow you to easily execute code each time a specific model class is saved or updated in the database.

Whenever a new model is saved for the first time, the creating and created events will fire. If a model already existed in the database and the save method is called, the updating / updated events will fire. However, in both cases, the saving / saved events will fire.

For example, let's define an Eloquent event listener in a service provider. Within our event listener, we will call the isValid method on the given model, and return false if the model is not valid. Returning false from an Eloquent event listener will cancel the save / update operation:

  1. <?php
  2. namespace App\Providers;
  3. use App\User;
  4. use Illuminate\Support\ServiceProvider;
  5. class AppServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * Bootstrap any application services.
  9. *
  10. * @return void
  11. */
  12. public function boot()
  13. {
  14. User::creating(function ($user) {
  15. return $user->isValid();
  16. });
  17. }
  18. /**
  19. * Register the service provider.
  20. *
  21. * @return void
  22. */
  23. public function register()
  24. {
  25. //
  26. }
  27. }

Observers

If you are listening for many events on a given model, you may use observers to group all of your listeners into a single class. Observers classes have method names which reflect the Eloquent events you wish to listen for. Each of these methods receives the model as their only argument. Laravel does not include a default directory for observers, so you may create any directory you like to house your observer classes:

  1. <?php
  2. namespace App\Observers;
  3. use App\User;
  4. class UserObserver
  5. {
  6. /**
  7. * Listen to the User created event.
  8. *
  9. * @param User $user
  10. * @return void
  11. */
  12. public function created(User $user)
  13. {
  14. //
  15. }
  16. /**
  17. * Listen to the User deleting event.
  18. *
  19. * @param User $user
  20. * @return void
  21. */
  22. public function deleting(User $user)
  23. {
  24. //
  25. }
  26. }

To register an observer, use the observe method on the model you wish to observe. You may register observers in the boot method of one of your service providers. In this example, we'll register the observer in the AppServiceProvider:

  1. <?php
  2. namespace App\Providers;
  3. use App\User;
  4. use App\Observers\UserObserver;
  5. use Illuminate\Support\ServiceProvider;
  6. class AppServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * Bootstrap any application services.
  10. *
  11. * @return void
  12. */
  13. public function boot()
  14. {
  15. User::observe(UserObserver::class);
  16. }
  17. /**
  18. * Register the service provider.
  19. *
  20. * @return void
  21. */
  22. public function register()
  23. {
  24. //
  25. }
  26. }