In this tutorial you will learn about the Laravel Eloquent ORM and its application with practical example.
What is Eloquent ORM?
One of the most important feature of the laravel framework is that, it comes with built in ORM (Object Relation Mapping) called Eloquent ORM.
Eloquent ORM refer to an advanced implementation of the PHP Active Record Pattern, which makes it very easy to interact with application database. Eloquent ORM is the very powerful yet very expressive ORM, which allow us to work with the database objects and relationships using much eloquent and expressive syntax. In Laravel, each database table is mapped into corresponding eloquent model and each of the eloquent model object include various methods for retrieving and updating the database.
Eloquent ORM CRUD Operations
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 previous article, so we will create new “Post” model using following artisan command –
1 |
php artisan make:model Post |
Let’s open the newly generated model file, at this point your model should look like as following –
1 2 3 4 5 6 7 8 9 10 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // } |
just edit your model as following –
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $primaryKey = 'id'; protected $table= 'posts'; protected $fillable = ['title','body','published','hits','created_at','updated_at']; } |
Eloquent ORM Create
To insert a record in database table we need to create a model instance, set or assign attributes values and then call save() method as following –
1 2 3 4 5 6 7 |
$post = new Post; $post->title = 'First Laravel Post'; $post->body = 'This is my first laravel article'; $post->save() |
In Laravel, we have two other methods to insert a record in database table(firstOrCreate and firstOrNew). The firstOrCreate method will try to retrieve the record matching to the column value pair. If the record not found in the table, a record will be inserted with the given column value pair. similarly, firstOrNew method method will try to retrieve the record matching to the column value pair. If the record not found in the table, a new model instance will be created with the given column value pair then you need to call save method to save the record.
1 2 3 4 5 |
// Retrieve the post by the attributes, or create it if it doesn't exist... $post= App\Post::firstOrCreate(['title' => 'Laravel 5']); // Retrieve the post by the attributes, or instantiate a new instance... $post= App\Post::firstOrNew(['title' => 'Laravel 5']); |
Eloquent ORM Read
Retrieving all records
In Laravel, all records can be retrieved from a table using all() method as following –
1 |
$posts= App\Post::all(); |
and you can loop through resultset for individual records as following –
1 2 3 |
foreach ($posts as $post) { echo $post->title; } |
Using Where Clause
1 |
$posts= App\Post::where('id', 1)->get(); |
Where Clause with Additional Constraints
1 2 3 |
$posts= App\Post::where('published', 1) ->orderBy('title', 'desc') ->get(); |
Retrieving Single Records
In Laravel, single record can be retrieved using find() and first() method as following –
1 2 3 4 5 |
// Retrieve a record by primary key... $post= App\Post::find(1); // Retrieve the first record matching the query constraints... $post= App\Post::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.
1 2 3 |
$post= App\Post::findOrFail(1); $post= App\Post::where('hits', '>', 5000)->firstOrFail(); |
Retrieving Aggregates
In Laravel, you can use aggregate functions like count, min, max, avg, sum etc. as following –
1 2 3 |
$published_count= App\Post::where('published', 1)->count(); $max_hits = App\Post::where('published', 1)->max('hits'); |
Eloquent ORM Update
To update a record you have to retrieve it first, set values for attributes that you want to update, and then call the save method.
1 2 3 4 5 |
$post= App\Post::find(1); $post->body= 'This is my first post'; $post->save(); |
Eloquent ORM Delete
To delete a record in laravel, simply call the delete method as following –
1 2 |
$post = App\Post::find(1); $post->delete(); |
You can delete a record directly using destroy method instead of retrieving it first, to do so simply call destroy method passing single or multiple primary keys as following –
1 2 3 4 5 |
App\Post::destroy(1); App\Post::destroy([1, 2, 3]); App\Post::destroy(1, 2, 3); |
You can also call delete method on query result set as following –
1 |
$deletedPosts = App\Post::where('published', 0)->delete(); |
Mass assignment
Laravel model allow us to assign multiple attributes values while creating model instance using the mass assignment. In Laravel model using the $fillable property we can declare array of attributes that is mass-assignable. For security concern Laravel supports a $guarded property which declare array of attributes that you do not want to be mass assignable.
Example:-
1 2 3 4 5 6 |
class User extends Model { protected $fillable = ['name', 'email']; protected $guarded = ['id', 'password']; } |
Soft Deleting
In Laravel, a soft deleted record is not actually removed from your database instead a deleted_at attribute is set for that record. Records with non-null deleted_at value are considered as soft deleted. To enable soft deletes for a laravel model, simply use the Illuminate\Database\Eloquent\SoftDeletes trait on the model and add the deleted_at column to your $dates property.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; // import SoftDeletes trait use Illuminate\Database\Eloquent\SoftDeletes; 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
By default soft deleted records are not included in the query result-set. However, if you want to include soft deleted records in query result, it can be done using withTrashed method in query.
Example:-
1 2 3 |
$posts = App\Post::withTrashed() ->where('published', 1) ->get(); |
Retrieving Only Soft Deleted Models
If you want to retrieve soft deleted records only, it can be done using onlyTrashed method as following –
Example:-
1 2 3 |
$posts = App\Post::onlyTrashed() ->where('published', 1) ->get(); |
Determine if Soft Deleted
If you want to check if a record has been soft deleted or not, use the trashed method as following –
1 2 3 4 |
if($post->trashed()) { // } |
Restoring Soft Deleted Models
Soft deleted record can also be recovered using restore method as following –
1 2 3 |
App\Post::onlyTrashed() ->where('published', 1) ->restore(); |
Permanently Deleting Models
If you want to permanently remove a soft deleted record from the database, it can be done using forceDelete method as following –
Example 1:-
1 |
$post->forceDelete(); |
Example 2:-
1 |
App\Post::onlyTrashed()->find(10)-> forceDelete(); |