Eloquent ORM: Inserting and Updating Data in Laravel


Laravel's Eloquent ORM (Object-Relational Mapping) simplifies database interactions by allowing you to work with database records as objects. In this guide, we'll explore how to insert and update data using Eloquent, a powerful feature of the Laravel framework.


1. Defining Eloquent Models


Start by defining an Eloquent model that represents a database table. For example, if you have a `users` table, create a `User` model using Artisan:


        
php artisan make:model User

2. Inserting Data


To insert a new record, create an instance of the model, set its attributes, and call the `save` method:


        
$user = new User;
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->save();

You can also use the `create` method to insert a new record in a single step:


        
User::create([
'name' => 'Jane Smith',
'email' => 'janesmith@example.com',
]);

3. Updating Data


To update an existing record, retrieve it using the model, modify its attributes, and call the `save` method:


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

Alternatively, you can use the `update` method for mass updates based on conditions:


        
User::where('email', 'johndoe@example.com')
->update(['name' => 'New Name']);

4. Mass Assignment


Laravel provides a convenient way to allow or restrict mass assignment of model attributes. Use the `fillable` or `guarded` properties in your model to define which attributes can be mass-assigned. This helps protect your application from overwriting unintended fields during mass updates.


5. Timestamps


Eloquent models automatically manage timestamps like `created_at` and `updated_at`. If your table has these columns, Eloquent will update them when inserting or updating records. To disable timestamps, set the `timestamps` property in your model to `false`.


6. Soft Deletes


Laravel supports soft deletes for records. To enable soft deletes, add the `SoftDeletes` trait to your model and define a `deleted_at` column in your table. Soft deleted records are not physically removed from the database but are marked as deleted, allowing for easy recovery if needed.


Conclusion


Laravel's Eloquent ORM simplifies data manipulation in your web applications. In this guide, you've learned how to define models, insert new records, update existing records, handle mass assignment, and work with timestamps and soft deletes. Eloquent's elegant syntax and powerful features make it a fantastic choice for working with databases in Laravel.

For further learning, consult the official Laravel documentation and explore practical tutorials and examples related to Eloquent ORM in Laravel web development.