How To Define Models In Laravel Framework With An Example

admin_img Posted By Bajarangi soft , Posted On 23-09-2020

The Eloquent ORM included with Laravel provides a beautiful, simple Active Record 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.

How To Define Models In Laravel Framework With An Example

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 demo

run above command to create model in app folder in laravel project.

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 demo --migration

php artisan make:model demo -m


How demo.php model created ? you can see below code 
<?php

namespace App\Models;

use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class demo
 * @package App\Models
 * @version September 03, 2020, 6:44 pm UTC
 *
 * @property string name
 * @property string desc
 */
class demo extends Model
{
    use SoftDeletes;

    public $table = 'demos';
   
    protected $dates = ['deleted_at'];

    public $fillable = [
        'name',
        'desc'
    ];

    /**
     * The attributes that should be casted to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'name' => 'string',
        'desc' => 'string'
    ];

    /**
     * Validation rules
     *
     * @var array
     */
    public static $rules = [
        
    ];
}

 

Related Post