Eloquent helps you easily create, read, update, and delete data in your database using simple code.
CRUD with Eloquent in Laravel
Introduction
Syntax
Laravel
Model::create([ 'column' => 'value' ]); Model::find(id); Model::where('column', 'value')->get(); $model = Model::find(id); $model->column = 'new value'; $model->save(); $model->delete();
Replace Model with your Eloquent model name like User or Post.
Use create() to add, find() or where() to read, save() to update, and delete() to remove data.
Examples
Laravel
User::create(['name' => 'Alice', 'email' => 'alice@example.com']);
Laravel
$user = User::find(1);
echo $user->name;Laravel
$user = User::find(1); $user->email = 'newemail@example.com'; $user->save();
Laravel
$user = User::find(1);
$user->delete();Sample Program
This example shows how to add a user, read their info, update their email, and then delete the user using Eloquent.
Laravel
<?php use App\Models\User; // Create a new user $newUser = User::create(['name' => 'Bob', 'email' => 'bob@example.com']); // Read user by ID $user = User::find($newUser->id); echo "User name: " . $user->name . "\n"; // Update user email $user->email = 'bob.new@example.com'; $user->save(); echo "Updated email: " . $user->email . "\n"; // Delete user $user->delete(); echo "User deleted.";
Important Notes
Make sure your model has protected $fillable set for mass assignment when using create().
Always check if find() returns a result before using it to avoid errors.
Deleting a record removes it permanently from the database.
Summary
Eloquent makes database actions simple with easy methods.
Use create(), find(), save(), and delete() for CRUD.
Always handle data carefully to avoid mistakes.
Practice
1. Which Eloquent method is used to add a new record to the database in Laravel?
easy
Solution
Step 1: Understand the purpose of
Thecreate()create()method in Eloquent is designed to add a new record to the database by passing an array of attributes.Step 2: Compare with other methods
find()retrieves a record,delete()removes a record, andupdate()modifies an existing record. None of these add new records.Final Answer:
create()-> Option AQuick Check:
Add new record =create()[OK]
Hint: Use create() to add new data fast [OK]
Common Mistakes:
- Confusing find() with create()
- Using update() to add new records
- Trying to delete() to add data
2. Which of the following is the correct syntax to find a record by its ID using Eloquent?
easy
Solution
Step 1: Recall Eloquent static method syntax
Eloquent uses static methods on the model class, soUser::find($id)is correct.Step 2: Identify incorrect syntax
User->find($id)is invalid becauseUseris a class, not an object.findById()does not exist.User.find()is not PHP syntax.Final Answer:
$user = User::find($id);-> Option CQuick Check:
Find by ID uses ::find() [OK]
Hint: Use double colon :: for static methods [OK]
Common Mistakes:
- Using arrow -> on class name
- Calling non-existent findById() method
- Using dot . notation like JavaScript
3. What will be the output of this code snippet assuming a user with ID 5 exists?
$user = User::find(5);
if ($user) {
$user->name = 'Alice';
$user->save();
echo 'Updated';
} else {
echo 'Not found';
}
medium
Solution
Step 1: find(5) execution
Since a user with ID 5 exists,User::find(5)returns an Eloquent model instance, making$usertruthy.Step 2: Update and save
Theif ($user)condition passes, sonameis set to 'Alice',save()persists it to the database, and 'Updated' is echoed.Final Answer:
Updated -> Option AQuick Check:
Record found and saved = 'Updated' [OK]
Hint: If find() returns object, save() updates record [OK]
Common Mistakes:
- Assuming save() is missing
- Thinking find() throws error if no record
- Expecting no output when record exists
4. Identify the error in this code that tries to delete a user by ID:
$user = User::find($id);
$user->delete($id);
medium
Solution
Step 1: Understand delete() method usage
In Eloquent,delete()is called on the model instance without any arguments to remove that record.Step 2: Identify the incorrect argument
The code incorrectly passes$idtodelete(), which expects no parameters. This causes an error.Final Answer:
delete() should be called without arguments -> Option DQuick Check:
delete() takes no parameters [OK]
Hint: Call delete() directly on model instance without args [OK]
Common Mistakes:
- Passing ID to delete() method
- Thinking delete() needs save() after
- Confusing delete() with static method
5. You want to update a user's email only if the user exists and the new email is not empty. Which code snippet correctly does this using Eloquent?
hard
Solution
Step 1: Check user existence and email validity
$user = User::find($id);
checks if
if ($user && !empty($newEmail)) {
$user->email = $newEmail;
$user->save();
}$userexists and$newEmailis not empty before updating, preventing errors or empty updates.Step 2: Compare other options
$user = User::find($id);
skips user existence check, risking errors if user is null.
if ($newEmail) {
$user->email = $newEmail;
$user->save();
}$user = User::findOrFail($id);
uses
$user->email = $newEmail;
$user->save();findOrFail()which throws exception if user missing, no email empty check.$user = User::where('id', $id)->update(['email' => $newEmail]);updates directly but does not check if$newEmailis empty.Final Answer:
$user = User::find($id);
-> Option B
if ($user && !empty($newEmail)) {
$user->email = $newEmail;
$user->save();
}Quick Check:
Check user and email before save [OK]
Hint: Always check user exists and data valid before save [OK]
Common Mistakes:
- Not checking if user exists before update
- Skipping validation of new email
- Using findOrFail without handling exceptions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
