How to create Model Laravel

Create a basic Laravel model with an example, from creating the model to configuring it for use.

Creating Models in Laravel

Models in Laravel are used to represent the data in the database. They are the source of data for the views and controllers in an application. Models are defined as classes that extend the Eloquent base class provided by Laravel.

To create a model in Laravel, simply run the command php artisan make:model ModelName in the terminal. This will create a new model class in the app directory of your project.


<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class ModelName extends Model
{
    //
}

The created model class is empty and ready to be filled with the properties and methods relevant to the model. To define the properties, add them to the model class as public variables.


<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class ModelName extends Model
{
    public $name;
    public $age;
    public $gender;
}

The properties declared in the model class are used to define the columns of the corresponding database table. The model class also provides other helpful methods to work with the database. For example, the create() method is used to create a record in the database.


ModelName::create([
    'name' => 'John Doe',
    'age' => 25,
    'gender' => 'male'
]);

This method will create a new record in the database with the given values. Other methods such as find(), where(), update(), and delete() are also provided by the Eloquent base class to make working with the database easier.

Models are an important part of any Laravel application and are used to represent the data in the database. They are defined as classes that extend the Eloquent base class provided by Laravel. They provide methods to make working with the database easier.

Answers (0)