Overview
Eloquent is an object-relational mapper (ORM) included with Laravel, which makes it easy for developers to interact with database operations using expressive, object-oriented syntax. In this tutorial, we will focus on the basic Create, Read, Update and Delete (CRUD) operations using Eloquent.
Before you begin, ensure you have a Laravel project set up. Eloquent relationships and models should also be defined appropriately in accordance with your database’s structure.
Inserting Records with Eloquent
To insert a new record into the database, you will first need to create a new instance of the model, set the model’s properties, and then call the save()
method.
$post = new Post;
$post->title = 'My first post';
$post->body = 'This is the body of my first post';
$post->save();
This code creates a new post with a title and body, and then saves it to the database.
Mass Assignment
If you have many fields to insert at once, you can also use mass assignment for convenience.
$post = Post::create([
'title' => 'My first post',
'body' => 'Content of the first post',
]);
In this case, ensure your model has the correct fields listed in its $fillable
or $guarded
array to protect against mass-assignment vulnerabilities.
Updating Records with Eloquent
To update a record, you need to retrieve the model from the database, change the attributes you wish to update, and then call save()
.
$post = Post::find(1);
$post->title = 'Updated post title';
$post->save();
This code snippet finds the post with an id
of 1 and updates its title.
Bulk Updates
If you need to update multiple records at once, Eloquent’s update()
method can be used in combination with a query.
Post::where('active', 1) ->update(['active' => 0]);
This updates the ‘active’ field of all posts that are currently active to be inactive.
Deleting Records with Eloquent
To delete a record, retrieve the model from the database and call the delete()
method.
$post = Post::find(1);
$post->delete();
This code snippet will delete the post with an id
of 1 from the database.
Soft Deleting
Laravel also provides a handy feature called ‘soft deletes’, which allows you to retain the records in the database and just mark them as ‘deleted’ using a timestamp. Here’s how to soft delete a record:
$post = Post::find(1);
$post->delete();
Note that, to use soft deletes, you must have a deleted_at
column in your table, and your model should use the SoftDeletes
trait.
Advanced Examples
Below are some advanced examples of how to insert, update, and delete records using Eloquent, Laravel’s ORM. These examples will cover more than just the basics, showcasing some of the powerful features Eloquent offers.
Insert with Relationship
Assuming a User
has many Posts
.
$user = App\Models\User::find(1);
$post = new App\Models\Post([
'title' => 'New Post',
'content' => 'Post content'
]);
$user->posts()->save($post);
Conditional Update
Updating a user’s status only if they are currently ‘active’.
$user = App\Models\User::find(1);
if ($user->isActive()) {
$user->status = 'inactive';
$user->save();
}
Force Delete
To permanently remove a soft deleted record.
$user = App\Models\User::withTrashed()->find(1);
$user->forceDelete();
Conditional Delete
Deleting a record based on a condition.
$user = App\Models\User::find(1);
if ($user->canBeDeleted()) {
$user->delete();
}
Delete with Relationship
Deleting all posts of a specific user.
$user = App\Models\User::find(1);
$user->posts()->delete();
Conclusion
Through this introductory guide, you’ve learned the basics of inserting, updating, and deleting records with Eloquent ORM. With Eloquent, these fundamental database operations are simplified, allowing for clear and expressive code.