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.
1php 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.
1<?php23namespace App\Models;45use Illuminate\Database\Eloquent\Model;67class ModelName extends Model8{9 //10}
Add table name in model
add your table name in your model file using the below example.
1<?php23namespace App\Models;45use Illuminate\Database\Eloquent\Model;67class ModelName extends Model8{9 /**10 * The table associated with the model.11 *12 * @var string13 */14 protected $table = 'model_name';15}
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.
1<?php23namespace App\Models;45use Illuminate\Database\Eloquent\Model;67class ModelName extends Model8{9 /**10 * The table associated with the model.11 *12 * @var string13 */14 protected $table = 'model_name';1516 /**17 * The primary key associated with the table.18 *19 * @var string20 */21 protected $primaryKey = 'model_id';22}
Insert Default Value ( Optional )
when you want to insert default for your any column like is_active => true
. laravel model provide options to set.
1/**2 * The model's default values for attributes.3 *4 * @var array5 */6 protected $attributes = [7 'is_active' => true,8 ];
Use Model to your controller
if you want example to use model in your controller, check below example.
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use App\Models\ModelName;7use Illuminate\Http\Request;89class ModelController extends Controller10{11 /**12 * Store a new modelName in the database.13 *14 * @param \Illuminate\Http\Request $request15 * @return \Illuminate\Http\Response16 */17 public function store(Request $request)18 {19 // insert new records20 $modelName = new ModelName;2122 $modelName->name = $request->name;2324 $modelName->save();25 }26}
if you get help, please share a post on your social network