eloquent models


The Eloquent ORM included with Laravel provides a beautiful ActiveRecord implementation for working with the database. Each database table has a corresponding Model which is used to interact with that table. Models allow us to query for data in the tables as well as insert new records into the table.

DEFINING MODELS

Artisan command make:model can be used to create models.

php artisan make:model User

--migration or -m can be added in that command to create migration along with the table.

php artisan make:model User --migration

php artisan make:model User -m

TABLE NAMES

The snake case plural name of the class will be used as the table name unless another name is specified. You can specify a custom table name by defining a table property on the model.

protected $table = 'users';

PRIMARY KEY

Eloquent provides a primary key column named id to each tables. You can define a custom name to override it.

	protected $primaryKey = 'u_id';

TIMESTAMPS

Eloquent adds created_at and updated_at columns to exist on the tables. you can set those property on the model to false to remove them. You can also set the $dateFormat property on your model to customize the date format o the timestamp.

public $timestamps = false;
protected $dateFormat = 'U';

You can set the CREATED_AT and UPDATED_AT constants in your model to customize the names of the columns used to store the timestamps.

const CREATED_AT = 'creation_date';
const UPDATED_AT = 'last_update';

DATABASE CONNECTIONS

All Eloquent models will use the default database connection configured for the application. You can use the $connection property to specify a different connection for the model if needed.

protected $connection = 'connection-name';

DATABASE QUERY

You can use the model to build queries and execute databse operations after creating a model and its associated database table.

<?php
use App\Flight;

$flights = App\Flight::all();

foreach ($flights as $flight) {
    echo $flight->name;
}
?>