Laravel Eloquent ORM


Eloquent ORM is a built-in feature of the laravel framework which provides you with Object Relation Mapping (ORM).
Eloquent ORM implements the PHP Active Record Pattern in a sophisticated way, so that it is very easy to communicate with application databases. Using Eloquent ORM, we are able to work with database objects and relationships in a more eloquent and expressive way.

Eloquent model objects that relate to every database table in Laravel contain various methods for retrieving and updating data in the database.
Eloquent ORM makes it incredibly easy to perform CRUD (Create, Read, Update, Delete) operations on Laravel Model, since we have already covered how to create Laravel Model in the previous article, so we will create new “Post” model using the following artisan command:

php artisan make:model Post

At this point we should see your newly generated model file looking like this:

namespace App;
use IlluminateDatabaseEloquentModel;
class Post extends Model

just edit your model as following –

<?php namespace App;
use IlluminateDatabaseEloquentModel;
class Post extends Model {
protected $primaryKey = 'id';
protected $table= 'posts';
protected $fillable = ['title','body','published','hits','created_at','updated_at'];

Eloquent ORM Create

A record in a database table can be inserted by creating an instance of the model, setting or assigning attribute values, and calling the save() method:

$post = new Post;
$post->title = 'First Laravel Post';
$post->body = 'This is my first laravel article';

Additionally, Laravel provides two ways to insert records in database tables (firstOrCreate and firstOrNew). It will try to retrieve the record whose columns and values match the firstOrCreate method. In the case of an unfound record, a new record will be inserted with the given column value pair. Accordingly, the firstOrNew method method will retrieve the records matching the value pair in the column. A new model instance will be created with the given column value pair if the record isn’t found in the table, then the save method needs to be called to save it.

// Retrieve the post by the attributes, or create it if it doesn't exist...
$post= AppPost::firstOrCreate(['title' => 'Laravel 5']);

Eloquent ORM Read

From a table in Laravel can be done by calling all() method as follows:

$posts= AppPost::all();

For individual records, you can loop through the resultset using:

foreach ($posts as $post) {
echo $post->title;

Using Where Clause

$posts= AppPost::where('id', 1)->get();

Where Clause with Additional Constraints

$posts= AppPost::where('published', 1)
->orderBy('title', 'desc')

Retrieving Single Records
In Laravel, single record can be retrieved using find() and first() method as following –

// Retrieve a record by primary key...
$post= AppPost::find(1);
// Retrieve the first record matching the query constraints...
$post= AppPost::where('published', 1)->first();

Record Not Found Exceptions
In Laravel, the findOrFail() and firstOrFail() methods retrieves the first result of the query and if record is not found an exception is thrown.

$post= AppPost::findOrFail(1);
$post= AppPost::where('hits', '>', 5000)->firstOrFail();

Retrieving Aggregates
In Laravel, you can use aggregate functions like count, min, max, avg, sum etc. as following –

$published_count= AppPost::where('published', 1)->count();
$max_hits = AppPost::where('published', 1)->max('hits');

Eloquent ORM Update

Changing a record requires retrieving it first, setting values for the attributes you want to change, and then calling the save method.

$post= AppPost::find(1);
$post->body= 'This is my first post';

Eloquent ORM Delete

Delete a record in Laravel by calling the delete method –

$post = AppPost::find(1);

Rather than retrieving a record first, you can directly delete a record by calling destroy and passing either one or more primary keys as shown below:

AppPost::destroy([1, 2, 3]);
AppPost::destroy(1, 2, 3);

Alternatively, you can call the delete method on query result set as follows:

$deletedPosts = AppPost::where('published', 0)->delete();

Mass assignment
By using the mass assignment feature, we can assign several attributes values to a model instance. A Laravel model has an $fillable property that allows us to declare arrays of attributes that can be assigned in bulk. To ensure the security of your application, Laravel provides a $guarded property that declares an array of attributes that should not be mass-assigned.

class User extends Model
protected $fillable = ['name', 'email'];
protected $guarded = ['id', 'password'];

Soft Deleting
Laravel’s soft deleted records are not actually removed from the database but instead are assigned to the deleted_at attribute. Soft deletion is considered to be records with non-null deleted_at values. The easiest way to enable soft deletes for a laravel model is by using the Illuminate/Database/Eloquent/SoftDeletes trait and adding the deleted_at field to the $dates property.

<?php namespace App;
use IlluminateDatabaseEloquentModel;
// import SoftDeletes trait
use IlluminateDatabaseEloquentSoftDeletes;
class Post extends Model {
// using the SoftDeletes trait
use SoftDeletes;
protected $table = 'posts';
protected $dates = ['deleted_at'];
protected $fillable = ['title','body'];

Including Soft Deleted Models
Whenever a query is run, soft deleted records are not included in the results. If, however, you would like to include soft deleted records in your query result, it can be done by using the withTrashed method.

$posts = AppPost::withTrashed()
->where('published', 1)

Retrieving Only Soft Deleted Models
There are a number of ways to retrieve only soft deleted records. To do this, you can use the onlyTrashed method –

$posts = AppPost::onlyTrashed()
->where('published', 1)

Determine if Soft Deleted
Record Was Trashed If you want to see whether a record has been trashed or not, use


Restoring Soft Deleted Models
Soft deleted record can also be recovered using restore method as following –

->where('published', 1)

Permanently Deleting Models
Using the forceDelete method, you can permanently eliminate a softly deleted model from your database.
Example 1:-


Example 2:-

AppPost::onlyTrashed()->find(10)-> forceDelete();


Post a Comment (0)
Previous Post Next Post