0
0
Laravelframework~5 mins

CRUD with Eloquent in Laravel

Choose your learning style9 modes available
Introduction

Eloquent helps you easily create, read, update, and delete data in your database using simple code.

When you want to save a new user to your database.
When you need to show a list of products on a webpage.
When you want to change details of an existing order.
When you want to remove old or unwanted records from your database.
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
Adds a new user named Alice to the database.
Laravel
User::create(['name' => 'Alice', 'email' => 'alice@example.com']);
Finds the user with ID 1 and shows their name.
Laravel
$user = User::find(1);
echo $user->name;
Changes the email of user with ID 1 and saves it.
Laravel
$user = User::find(1);
$user->email = 'newemail@example.com';
$user->save();
Deletes the user with ID 1 from the database.
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.";
OutputSuccess
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.