Laravel Eloquent: Updating and Retrieving Records

AuthorSumit Dey Sarkar

Pubish Date03 Mar 2024


In this tutorial, we will learn the ins and outs of efficient data management in Laravel using Eloquent ORM.

Laravel Eloquent: Updating and Retrieving Records

Eloquent update and get record back

In Laravel, you can update and retrieve records from a database using Eloquent, the built-in ORM (Object-Relational Mapping). Here's a basic example:

Updating a Record

To update a record, you can use the update method on the Eloquent model. For example, if you have a User model and want to update the name of a user with the ID of 1:

$user = User::find(1);
$user->name = 'New Name';

This code retrieves the user with ID 1, updates the name, and then saves the changes to the database.

Retrieving a Record

To retrieve a record, you can use methods like find, first, or where depending on your specific requirements.

Using find:

$user = User::find(1);

This retrieves the user with ID 1.

Using first:

$user = User::where('email', '')->first();

This retrieves the first user with the specified email.

Using where:

$users = User::where('status', 'active')->get();

This retrieves all users with the status 'active'.

Remember to replace User with the actual name of your model.

Ensure your model is correctly set up with the database table and fields you need to work with. An easy and expressive approach to work with your database tables is with Laravel Eloquent.

Comments 0

Leave a comment