LARAVEL

Laravel Eloquent ORM INSERT, READ, UPDATE, DELETE


 Below are examples demonstrating how to perform INSERT, READ, UPDATE, and DELETE operations using Laravel's Eloquent ORM.

 

1. INSERT (Create):

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();

 

2. READ (Retrieve):

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();

 

3. UPDATE:

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();

 

4. DELETE:

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();

 

Note:

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.


LARAVEL