Laravel Model Tutorial with Examples | Laravel Eloquent ORM

Laravel Model Tutorial | Laravel Eloquent ORM

 

Laravel Model
Laravel Model

 

Laravel framework provides a very elegant, clean and robust database handling layer known as Laravel Model or Laravel Eloquent Model. The Laravel Model is a crux of any well-designed web application.

 

What is a Laravel Model?

Models in Laravel acts as a bridge between your laravel application and the underlying database tables.

In the MVC framework, Model is an integral part of the application which provides the database access layer to read/write from the database. The Laravel Eloquent Model primarily controls the data flow between the controller and the actual database – MySQL, etc.

From a programmer’s standpoint, Eloquent Model in Laravel is an object-oriented class which contains the code to interact with the database.

Each Eloquent Model in Laravel corresponds to the specific database table.

For example, the User() model class will represent the “users” table in the database.

Laravel Models are also known as Laravel Eloquent Model. This means that we can easily ‘CREATE, RETRIEVE, UPDATE, or DELETE’ any database record using this Eloquent Model class.

 

Technically Speaking…

From web developers viewpoint, a Model provides a convenient interface for converting an application object into database table records and vice versa. Also, note that Laravel Model file has the same name as Model class name.

Laravel Model path:

In Laravel 5.5, the models were created inside the “app” folder.

So, in nutshell there’s one class per table, which is responsible for retrieving, representing, and persisting data in that table.

 

Best Laravel Development Company

Laravel Development Company in Delhi NCR

What is Laravel Eloquent ORM?

Laravel Model is also known as eloquent ORM.

Let’s explore it.

Laravel Eloquent is an ActiveRecord ORM. It is a database abstraction layer that provides a unified interface to communicate with multiple database types.

The term “ActiveRecord” means that a single Eloquent class is responsible for not only providing the ability to interact with the table as a whole. For example User::all() gets all users from the associated table, but also representing an individual table row (e.g., $user = new User).

Additionally, each instance is capable of managing its own persistence; you can call:

      $user->save() or $user->delete().

 

If you are a beginner to Laravel Framework, then we recommend you to read the following topics:

 

How to Create a Model in Laravel?

Models are the backbone of any well-designed web application. Creating and defining a new Laravel model is very easy. From laravel 5 onwards, laravel developers can make use of the laravel artisan commands to create and define the laravel model.

The following is the Laravel Artisan command to create model:

$ php artisan make:model Candidate -m

Model created successfully.
Created Migration: 2019_06_24_215705_create_candidate_table

Note that here the -m option additionally tells Laravel to create a companion migration.

New Model file:

You’ll find the new model in app/Todolist.php. It looks like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Candidate extends Model
{
     //
}

Here, Candidate is a model which will be used to retrieve and store information from the candidate’s database table.

NOTE: Like other web frameworks, Laravel also expects the model name to be in the singular form
(Candidate), and the underlying table names to be a plural form (Candidates).

So, from the above example, you can observe that a Laravel model is just a PHP class that extends the default Model class.

Note that A model is only useful when it’s associated with an underlying database table.

Understanding Laravel Model Class Attributes

Each Laravel Model class has certain default attributes:

Laravel Model Table name

The default behavior for table name is that Laravel “snake cases” and pluralizes your
class name, so Candidate model would access a table named candidates. If you’d like to customize the name, set the $table property explicitly on the model:

             protected $table = ‘candidate_table’;

Laravel Model Primary key

By default, Laravel assumes that each database table would have an auto-incrementing integer primary key which will be named as idOptionally, if you want to modify the name of your primary key, then change the $primaryKey property as below:

     protected $primaryKey = ‘candidate_id’;

Laravel Model Timestamps

The Model expects that all database tables would have two timestamp fields – created_at and updated_at as columns.  To disable the $timestamps functionality:
         public $timestamps = false;

 

Laravel Development Company in Delhi India

Laravel Development Company in Delhi India

How does the eloquent Model connect to Database?

By default, all the laravel models use the default database connection as specified in the global database configuration file. To specify a different database connection for a model, make us of the               $connection property.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Candidate extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = ‘connection-name’;
}

 

Well, in the next section, we will learn how to perform the basic SQL CRUD operations using Laravel Model.

 

Using Laravel Model to retrieve Data from Database

After you setup database configuration and defined the set of models for your web application, you can easily insert, retrieve data from the associated database table.

As we have already discussed that each Laravel Model represents a specific table in the database.

So, imagine a Model as a SQL query builder which internally uses SQL queries to perform requested database operations.

To retrieve the data from the database table, ask the associated Laravel Model. For example to retrieve all data rows from the “candidates” table, use the Candidate()::all() method:

<?php

      $candidates = App\Candidate::all();

      foreach ($candidates as $candidate)

      {
         echo $candidate->name;
       }

?>

Here, the Laravel Eloquent all() method will return all of the results in the model’s table.

Inserting data using Laravel Model

The following steps would insert data using a model in laravel:

Steps to insert new data to the Laravel Model:
Step1:   First of all create a new instance of associated Laravel Model
Step2:   Set values of the table attributes that the Model represents.
Step3:   Call save() method on the newly created model instance (object).

<?php

namespace App\Http\Controllers;

use App\Candidate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CandidateController extends Controller
{
    /**
      * Create a new candidate instance.
      *
      * @param Request $request
      * @return Response
      */
     public function store(Request $request)
     {
         // Validate the request…

        $candidate = new Candidate();

        $candidate->name = $request->name;

        $candidate->save();
    }
}

Update Existing row using Laravel Models

The Laravel Model’s save() method can also be used to update the existing model record in the database table. The following steps will update related laravel model.

Steps to update model:

Step1:   Retrieve the specific Model Record to update
Step2:   Set or change any attributes you want to modify
Step3:   Call the save() method.

Laravel Model Update Example

$candidate = App\Candidate::find(1);

$candidate->address = ‘New Address here’;

$candidate->save();

NOTE: As a result of the above code, the updated_at timestamp field will automatically be updated in the corresponding database table.

Deleting data row using Laravel Models

Deleting a data row from the table is very simple using Laravel Models. The delete() method is used to delete data from the associated database table.

$candidate = App\Candidate::find(1);

$candidate->delete();

 

Subscribe to Newsletter

 

End Notes!

We have now learned the fundamental concepts behind Laravel Model and the database CRUD operations can be performed using the Models. Laravel developers can use Models to retrieve, create, update or delete any data from the database tables associated with the Model. Each Model represents a specific database table.

 

Further reading:

Laravel 5.8 Eloquent

Laravel Cloudways

Laravel Eloquent Tips & Tricks

Leave a Reply

Your email address will not be published. Required fields are marked *