Laravel Making a Model


Example

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:

PropertyDescriptionDefault
protected $connectionDB connection nameDefault DB connection
protected $tableTable nameBy default, the class name is converted to snake_case and pluralized. For example, SpecialPerson becomes special_people
protected $primaryKeyTable PKid
public $incrementingIndicates if the IDs are auto-incrementingtrue
public $timestampsIndicates if the model should be timestampedtrue
const CREATED_ATName of the creation timestamp columncreated_at
const UPDATED_ATName of the modification timestamp columnupdated_at
protected $datesAttributes that should be mutated to DateTime, in addition to the timestamps attributes[]
protected $dateFormatFormat in which date attributes will be persistedDefault for current SQL dialect.
protected $withRelationships to eagerload with model[]
protected $hiddenAttributes omitted in model serialization[]
protected $visibleAttributes allowed in model serialization[]
protected $appendsAttribute accessors added to model serialization[]
protected $fillableAttributes that are mass-assignable[]
protected $guardedAttributes that are black-listed from mass assignment[*] (All attributes)
protected $touchesThe relationships that should be touched on save[]
protected $perPageThe number of models to return for pagination.15
5.0
PropertyDescriptionDefault
protected $castsAttributes that should be casted to native types[]