Laravel

Eloquent: Model

Making a Model

Model creation

Model classes must extend Illuminate\Database\Eloquent\Model. The default location for models is the /app directory.

A model class can be easily generated by the Artisan command:

php artisan make:model [ModelName]

This will create a new PHP file in app/ by default, which is named [ModelName].php, and will contain all the boilerplate for your new model, which includes the class, namespace, and using’s required for a basic setup.

If you want to create a migration file along with your Model, use the following command, where -m will also generate the migration file:

php artisan make:model [ModelName] -m

In addition to creating the model, this creates a database migration that is hooked up to the model. The database migration PHP file is located by default in database/migrations/. This does not—by default—include anything other than the id and created_at/updated_at columns, so you will need to edit the file to provide additional columns.

Note that you will have to run the migration (once you have set up the migration file) in order for the model to start working by using php artisan migrate from project root

In addition, if you wish to add a migration later, after making the model, you can do so by running:

php artisan make:migration [migration name]

Say for example you wanted to create a model for your Cats, you would have two choices, to create with or without a migration. You would chose to create without migration if you already had a cats table or did not want to create one at this time.

For this example we want to create a migration because we don’t already have a table so would run the following command.

php artisan make:model Cat -m

This command will create two files:

  1. In the App folder: app/Cat.php
  2. In the database folder: database/migrations/timestamp_creat_cats_table.php

The file we are interested in is the latter as it is this file that we can decide what we want the table to look like and include. For any predefined migration we are given an auto incrementing id column and a timestamps columns.

The below example of an extract of the migration file includes the above predefined columns as well as the addition of a the name of the cat, age and colour:

public function up()
    {
        Schema::create('cats', function (Blueprint $table) {

            $table->increments('id');    //Predefined ID
            $table->string('name');      //Name
            $table->integer('age');      //Age
            $table->string('colour');    //Colour
            $table->timestamps();        //Predefined Timestamps

        });
    }

So as you can see it is relatively easy to create the model and migration for a table. Then to execute the migration and create it in your data base you would run the following command:

php artisan migrate

Which will migrate any outstanding migrations to your database.


Model File Location

Models can be stored anywhere thanks to PSR4.

By default models are created in the app directory with the namespace of App. For more complex applications it’s usually recommended to store models within their own folders in a structure that makes sense to your apps architecture.

For example, if you had an application that used a series of fruits as models, you could create a folder called app/Fruits and within this folder you create Banana.php (keeping the StudlyCase naming convention), you could then create the Banana class in the App\Fruits namespace:

namespace App\Fruits;

use Illuminate\Database\Eloquent\Model;

class Banana extends Model {
    // Implementation of "Banana" omitted
}

Model configuration

Eloquent follows a “convention over configuration” approach. By extending the base Model class, all models inherit the properties listed below. Unless overridden, the following default values apply:

Property Description Default
protected $connection DB connection name Default DB connection
protected $table Table name By default, the class name is converted to snake_case and pluralized. For example, SpecialPerson becomes special_people
protected $primaryKey Table PK id
public $incrementing Indicates if the IDs are auto-incrementing true
public $timestamps Indicates if the model should be timestamped true
const CREATED_AT Name of the creation timestamp column created_at
const UPDATED_AT Name of the modification timestamp column updated_at
protected $dates Attributes that should be mutated to DateTime, in addition to the timestamps attributes []
protected $dateFormat Format in which date attributes will be persisted Default for current SQL dialect.
protected $with Relationships to eagerload with model []
protected $hidden Attributes omitted in model serialization []
protected $visible Attributes allowed in model serialization []
protected $appends Attribute accessors added to model serialization []
protected $fillable Attributes that are mass-assignable []
protected $guarded Attributes that are black-listed from mass assignment [*] (All attributes)
protected $touches The relationships that should be touched on save []
protected $perPage The number of models to return for pagination. 15
Property Description Default
------ ------ -----
protected $casts Attributes that should be casted to native types []

Update an existing model

$user = User::find(1);
$user->name = 'abc';
$user->save();

You can also update multiple attributes at once using update, which does not require using save afterwards:

$user = User::find(1);
$user->update(['name' => 'abc', 'location' => 'xyz']);

You can also update a model(s) without querying it beforehand:

User::where('id', '>', 2)->update(['location' => 'xyz']);

If you don’t want to trigger a change to the updated_at timestamp on the model then you can pass the touch option:

$user = User::find(1);
$user->update(['name' => 'abc', 'location' => 'xyz'], ['touch' => false]);

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow