Laravel Model Tutorial with Examples

img
Jun
28
Spread the love

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, the 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, the Eloquent Model in Laravel is an object-oriented class that 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 the web developers viewpoint, a Model provides a convenient interface for converting an application object into database table records and vice versa. Also, note that the 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

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 a 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 that 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 the 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 id. Optionally, 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

How does the eloquent Model connect to the 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 set up 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 that 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();

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.

Leave a Reply

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

  • Broadband Speed Check
    Spread the love Broadband speed refers to the data transfer rate from the internet to your computer.  Broadband speed tests measure […]
  • Compare Internet Service Providers (DSL)
    Spread the love   Verizon DSL Qwest DSL Deluxe AT&T U-Verse High Speed Internet. Maximum connection speed (Download / Upload)* 0.5 -1 […]
  • Compare High Speed 56K Dialup ISP
    Spread the love   PeoplePC AT&T Copper.net EarthLink ISP.com AOL Time usage/m Unlimited Unlimited 200 hr Unlimited Unlimited Unlimited […]
  • DSL vs Cable Internet – Differences between DSL and Cable Internet
    Spread the love DSL internet Cable internet Data transmission via phone line Data transmission via coaxial cable line Connected through DSL modem […]
  • VoIP – Bonus Features
    Spread the love Unlike landline phone service, VoIP providers often provide many bonus features for free.  Some of them are very useful to […]
  • Virtual Telephone Number – What is a virtual telephone number?
    Spread the love A virtual telephone number is simply a phone number that doesn’t have a directly-associated phone line.  It is a vanity number […]
  • Satellite VoIP
    Spread the love The market of VoIP has been expanding rapidly over the past few years.  VoIP allows the transmission of voice signals over the […]
  • VoIP – FAQ
    Spread the love VoIP is a relatively new phone service to many consumers.  Some of you may have hesitations when transferring your phone service from […]
  • Cable Internet Service Providers
    Spread the love Comcast Cable Internet Maximum connection speed: 8 Mbps / 384 kbps (download speed up to 100 times faster than 56K dialup) $75 Cash […]
  • Broadband DSL. What does DSL stand for?
    Spread the love DSL stands for “Digital Subscriber Line”. It is a family of technologies that provides digital data transmission over the wires of […]
  • Broadband Internet
    Spread the love Broadband Internet, also called High Speed Internet, is an internet connection offering high data transmission rate of 256 Kbps […]
  • Wireless Internet Service Providers
    Spread the love AT&T Wi-Fi service can connect you with public wireless high speed internet access at speeds much faster than dialup when you are […]
  • Satellite Internet Providers
    Spread the love HughesNetTM offers affordable, super-fast, always-on, satellite Internet access and is available anywhere in the contiguous […]
  • VoIP for Small Business
    Spread the love VoIP, or voice over internet protocol, is a technology that has revolutionized the way businesses communicate today. This technology […]
  • Wireless Internet / Wi-Fi
    Spread the love How does wireless internet work?  Wireless internet transfers digital data using radio frequency. Wi-Fi is the leading wireless […]
  • Ten Tips for Choosing a VoIP Provider
    Spread the love What should you consider when choosing a VoIP provider? Read our simple tips and do your own VoIP comparisons before making your […]
  • Satellite Internet
    Spread the love Satellite Internet Access is probably the most expensive high speed internet service for home users. However, in rural or remote […]
  • Best VoIP Providers
    Spread the love VoIPo Residential VoIP Key Features: Unlimited Calls to US/Canada Over 38 Calling Features 2nd Line (Cloned) Free Equipment Free […]
  • ISP: Tips for Choosing a Good Broadband ISP
    Spread the love For those who are relocating or moving from dialup to broadband internet access, choosing a broadband ISP can cause some headaches. […]
  • 56K Dialup ISP / High Speed Dialup ISP
    Spread the love PeoplePC Accelerated Unlimited internet access Accelerated technology increases speed by up to 5X Smart dialer technology (dial the […]