Hello Friends,

Welcome To Infinitbility!

In this article, we can create a model in laravel and use it in the controller with an example.

This article only explains the required things to learn and use laravel model.

Model

Eloquent models allow you to insert, update, and delete records from the table as well.

Eloquent

Laravel use Eloquent, When using Eloquent, you have to create a separate model for each table.

Create model

create model using laravel make model cammand

open cmd Or Terminal to your project dir and use below cammand.

php artisan make:model ModelName

after run Artisan make model cammand, check your project/App/Models folder.

You get ModelName.php file something like below code.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{
    //
}

Add table name in model

add your table name in your model file using the below example.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'model_name';
}

Add Primary Key in model

Laravel model uses default id as your model primary key but if you use another name for your primary id column then you need to declare.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ModelName extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'model_name';

     /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'model_id';
}

Insert Default Value ( Optional )

when you want to insert default for your any column like is_active => true. laravel model provide options to set.


    /**
     * The model's default values for attributes.
     *
     * @var array
     */
    protected $attributes = [
        'is_active' => true,
    ];

Use Model to your controller

if you want example to use model in your controller, check below example.

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\ModelName;
use Illuminate\Http\Request;

class ModelController extends Controller
{
    /**
     * Store a new modelName in the database.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // insert new records
        $modelName = new ModelName;

        $modelName->name = $request->name;

        $modelName->save();
    }
}

Thanks for reading…

More tutorial form Laravel

Yajra issue after install in laravel

Laravel call function from another class

laravel pagination with customization

How to solve page expired error in laravel for webhooks, ajax, and form

Laravel Model

Laravel Clear cache, config, view and Routes

how to force Laravel to use https in URL and assets