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:
php artisan make:model Flight
If you would like to generate a database migration when you generate the model, you may use the --migration
or -m
option:
php artisan make:model Flight --migration
php artisan make:model Flight -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:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
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:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_flights';
}
Primary Keys
Eloquent will also assume that each table has a primary key column named id
. You may define a protected $primaryKey
property to override this convention:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'flight_id';
}
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will automatically be cast to an int
. 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
:
<?php
class Flight extends Model
{
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
}
If your primary key is not an integer, you should set the protected $keyType
property on your model to string
:
<?php
class Flight extends Model
{
/**
* The "type" of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
}