Laravel Models

In this tutorial you will learn about the Laravel Models and its application with practical example.

What is Model?

In MVC framework, the letter “M” stands for Model. Model are means to handle the business logic in any MVC framework based application. In Laravel, Model is a class that represents the logical structure and relationship of underlying data table. In Laravel, each of the database table has a corresponding “Model” that allow us to interact with that table. Models gives you the way to retrieve, insert, and update information into your data table.All of the Laravel Models are stored in the main app directory.

Creating a Model

Model can be created simply using make:model artisan command as following –

Syntax:-

Replace <model-name> with name you like for model you are creating.

Once the above command is executed, a model class file with some basic model code will be created in the App directory.

Example:-

Step 1:- Open the command prompt and execute the following Artisan command –

Step 2:- As the above command is executed, a model will be generated named Post as app/Post.php. Let’s open the newly generated model file, at this point your model should look like as following –

Note that every Eloquent models we create extends the Illuminate\Database\Eloquent\Model class.

Table Name

The plural form of the model name is used as the default table name for the corresponding, custom table name can also be defined explicitly using $table property as following –

Primary Key

In Laravel, it is assumed that each of model table by default has a primary key column named id, it can be overridden explicitly using $primaryKey property as following –

Timestamp

In Laravel, each of the Eloquent Model have added the two columns (created_at and updated_at) in all of your database tables, If you do not want to have these columns added to your database table, set the $timestamps property on your model to false as following -<?php

 

 

 

 

In this tutorial we have learn about the Laravel Models and its application with practical example. I hope you will like this tutorial.