Laravel

Laravel TutorialChange default routing behaviour in Laravel 5.2.31 +CustomException class in LaravelDeploy Laravel 5 App on Shared Hosting on Linux ServerLaravel ArtisanLaravel AuthenticationLaravel AuthorizationLaravel Blade TemplatesLaravel CashierLaravel CollectionsLaravel Common Issues & Quick FixesLaravel ConstantsLaravel ControllersLaravel Cron basicsLaravel Cross Domain RequestLaravel Custom Helper functionLaravel DatabaseLaravel Database MigrationsLaravel Database SeedingLaravel Directory StructureLaravel DockerLaravel EloquentLaravel Eloquent : RelationshipLaravel Eloquent: Accessors & MutatorsLaravel Eloquent: ModelLaravel Error HandlingLaravel Events and ListenersLaravel Filesystem / Cloud StorageLaravel Form Request(s)Laravel Getting started with laravel-5.3Laravel HelpersLaravel HTML and Form BuilderLaravel InstallationLaravel Installation GuideLaravel Introduction to laravel-5.2Laravel Introduction to laravel-5.3Laravel lumen frameworkLaravel Macros in Eloquent RelationshipLaravel MailLaravel MiddlewareLaravel ObserverLaravel PackagesLaravel PaginationLaravel Permissions for storageLaravel PoliciesLaravel QueuesLaravel RequestsLaravel Route Model BindingLaravel RoutingLaravel SeedingLaravel ServicesLaravel SocialiteLaravel Task SchedulingLaravel TestingLaravel Token Mismatch Error in AJAXLaravel use fields aliases in EloquentLaravel Useful linksLaravel ValetLaravel ValidationMultiple DB Connections in LaravelNaming Files when uploading with Laravel on WindowsRemove public from URL in laravelSparkpost integration with Laravel 5.4



Laravel Eloquent: Model

From WikiOD

Making a Model[edit | edit source]

Model creation[edit | edit source]

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[edit | edit source]

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[edit | edit source]

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

5.0

Property Description Default
protected $casts Attributes that should be casted to native types []

Update an existing model[edit | edit source]

$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]);

Credit:Stack_Overflow_Documentation