Table of contents
1.
Introduction
2.
Laravel Eloquent
2.1.
Creating the model
2.1.1.
Structure of the Model
2.2.
Table Names
2.3.
Primary keys
2.4.
Read Data
2.4.1.
Reading data with constraints
2.5.
Insert data
2.6.
Updating the Data with the save() method
2.7.
Delete Data
3.
Frequently Asked Questions
3.1.
Why do we use eloquent in Laravel?
3.2.
What is an eloquent relationship in Laravel?
3.3.
What is first () in eloquent?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Laravel Eloquent

Author Sanjana Yadav
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello there!!

Today, we will learn about Eloquent and its uses in Lavarel. Many of the complicated queries required to deal with relationships, insert, update, and remove database records, as well as search, filter, and limit query results, are abstracted using Eloquent. In this article, we will understand Eloquent in Laraval thoroughly.

Laravel Eloquent

Laravel Eloquent

Laravel is a PHP framework based on MVC. The letter 'M' stands for 'Model' in MVC architecture. A Model is essentially a method for querying data to and from a database table. Using Eloquent ORM, Laravel offers a simple method to accomplish this. Every table has a Model that interacts with it.

Models are built in the app directory. You may also put the model anywhere, and it will be loaded automatically based on the composer.json file.

To generate the model, we may use the following command:

php artisan make:model Example


We can also create the model using database migration:

php artisan make:model Example -m


or

php artisan make:model Example -migration

Creating the model

  1. Go to your project inside htdocs folder. Open the Git Bash window and enter the above command.
Creating the model

We can see that the model with name Example has been created successfully.

2. Below is created project in the app directory

created project in the app directory

Structure of the Model

The structure of the Model we just created is given below.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use HasFactory;
}


This means that the Example class extends the use Illuminate\Database\Eloquent\Model.

Must Read PHP Projects With Source Code

Table Names

We do not need to mention the table name for the Post model in laravel eloquent. Unless we supply the table name directly, the class's plural name( small case) will be used as the table name. In the given code, for example, the name of the class that operates on the table examples is Example. We may alternatively define the custom table by using the model class's $table property, as shown in the code below:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use HasFactory;
    protected $table = 'examples';  
}

 

The $table property in the previous code indicates that the Example class is using the examples table.

Primary keys

According to the eloquent model, each table has a primary key called 'id.' We may override this convention by giving the $primarykey property an alternative name.

<?php  
namespace App;  
use Illuminate\Database\Eloquent\Model;  

Class SampleClass extends Model  
{  
    protected $primaryKey = 'example_id';  
/** 
     * primary key of the table 
*/
}

In eloquent, the primary key is always an auto-incremented integer value. If we wish to provide the primary key a non-incrementing value, we must set the $incrementing property to 'false.'

Read Data

Let us now learn to retrieve data from the database. We will understand this through an example.

  1. We will first add two attributes to the class model.
    Example.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
    use HasFactory;
    protected $table = 'examples'; 
    protected $primaryKey='id'; 
}


2. Adding the route to retrieve the data from the database.
    Web.php

<?php  
use App\Example;  
Route::get('/readdata',function(){  
$posts=Example::all();  
foreach($posts as $post)  
{  
  echo $example->body;  
  echo '<br>';  
}  
});


In the above code, we use the all() function to obtain all the records from the database, and then we use the foreach loop to extract the body name of all the rows in the database.

Reading data with constraints

  1. If we want to get a specific record from the database, we use the find() function.
Route::get('/findfunc',function(){  
$posts=Example::find(2);  
return $examples->title;  
}); 


2. If we don't need to access the complete row, we may use the value() function to get the value of a single column.

Route::get('/findfunc',function(){  
$examples=Example::where('id',1)->value('title');  
return $examples;  
}); 

Insert data

Now we'll look at how to insert the data into a database. Consider the following example:

Route::get('/insertdata',function(){  
$example=new Example;  
$example->title='Sanjana';  
$example->body='QA Analyst';  
$example->save();  
}); 

Updating the Data with the save() method

Route::get('/updatedata',function(){  
  $example=Example::find(2);  
  $example->title='Akshita';  
  $example->body='Graphic Designer';  
  $example->save();  
  });

Delete Data

We will use the delete() function to remove data from the database, as illustrated below:

There are several methods for deleting the data.

  1. The first approach is to use the find() and remove() functions.
Route::get('/finddelete',function(){  
$example=Example::find(3);  
$example->delete();  
});


This will delete the record having id 3.

2. The second approach is to use the destroy() function.

Route::get('/destroyfunc',function(){  
Example::destroy(4);  
});  
This will delete the record having id 4.
To destroy more than one row,
Route::get('/destroyfunc',function(){  
Example::destroy([5,6]);  
});


This will delete the record having ids 5 and 6.

3. The third option is to execute the query.

Route::get('/deletethroughquery',function(){  
Examplet::where('id',7)->delete();  
});


This will delete the record having id 7.

Must Read: Laravel Facades

Frequently Asked Questions

Why do we use eloquent in Laravel?

For dealing with our database, the Eloquent ORM provided with Laravel provides a beautiful, simple ActiveRecord implementation. Each database table has its own "Model," which is used to interface with it.

What is an eloquent relationship in Laravel?

Relationships in Eloquent are specified as methods in our Eloquent model classes. Because relationships are also effective query builders, expressing them as methods allow for robust method chaining and querying capabilities.

What is first () in eloquent?

The Laravel Eloquent first() function helps us in retrieving the first entry from the database.

Conclusion

In this article, we learned about Eloquent in Lavarel in detail. We learned about its several functionalities with the help of examples.

We hope this blog has helped you understand Laravel Eloquent and how they function. You may read more about Laravel interview questions and much more here.

You can also visit our website to read more such blogs. Make sure you enroll in the courses we provide, take mock tests, solve problems, and interview puzzles. Also, you can prepare for interviews with interview experiences and an interview bundle.

Keep learning and keep growing, Ninjas!

Thank you
Live masterclass