Below are examples demonstrating how to perform INSERT, READ, UPDATE, and DELETE operations using Laravel's Eloquent ORM.
To insert a new record into the database using Eloquent ORM, you can use the create()
method or the model's constructor followed by the save()
method.
use App\Models\User;
// Using create() method
$user = User::create([
'name' => 'John Doe',
'email' => 'john@example.com',
'password' => bcrypt('password'),
]);
// Using model constructor and save() method
$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->password = bcrypt('password');
$user->save();
To retrieve records from the database using Eloquent ORM, you can use methods like all()
, find()
, where()
, etc.
use App\Models\User;
// Retrieve all users
$users = User::all();
// Retrieve a user by ID
$user = User::find(1);
// Retrieve users based on a condition
$users = User::where('age', '>', 18)->get();
To update an existing record in the database using Eloquent ORM, you can retrieve the record, modify its attributes, and then call the save()
method.
use App\Models\User;
// Retrieve the user to update
$user = User::find(1);
// Update user's attributes
$user->name = 'Jane Doe';
$user->email = 'jane@example.com';
// Save the changes to the database
$user->save();
To delete a record from the database using Eloquent ORM, you can retrieve the record and then call the delete()
method.
use App\Models\User;
// Retrieve the user to delete
$user = User::find(1);
// Delete the user
$user->delete();
Laravel's Eloquent ORM provides a simple and expressive way to perform CRUD operations on your database tables. By using Eloquent's methods and conventions, you can efficiently manage your application's data without writing complex SQL queries. This abstraction layer simplifies database interactions and improves the maintainability of your codebase.