Updating data in the database using the Laravel framework is a straightforward process. Here's a step-by-step guide on how to perform an update operation in Laravel.
1. Setup Route
First, define the routes in routes/web.php
for displaying the edit form and handling the form submission:
-
The
GET
route will display the edit form for the specific record. -
The
PUT
route will handle the update operation.
2. Create Controller Method
Next, create a controller method that will show the edit form and another method to update the record.
Run this command to generate a controller if you don’t have one:
Then, modify app/Http/Controllers/RecordController.php
to include the following methods:
Edit Method
Update Method
-
The
edit
method retrieves the specific record from the database and returns the edit form view. -
The
update
method validates the request data, finds the record, updates the fields, and saves the changes to the database.
3. Create/Edit Blade View
Now, create or modify the Blade view for the edit form. If the record to be updated is a Record
model, create the file resources/views/records/edit.blade.php
.
Edit Form (edit.blade.php)
Explanation:
-
The form sends a PUT request to the
update
route to update the record. -
We use
@method('PUT')
to simulate a PUT request (since HTML forms only support GET and POST). -
The
old()
function ensures that if there are validation errors, the old data is populated in the form fields. -
The
$record->name
,$record->email
, and$record->age
are used to pre-populate the form fields with the existing data.
4. Perform Validation
The update
method in the controller contains validation logic using the validate
method. This ensures the data submitted by the user meets certain criteria:
You can modify the validation rules as per your requirements.
5. Show Error Messages
If there are any validation errors, Laravel will automatically redirect the user back to the edit page with the validation messages. To display the errors in the form, you can add the following code in your Blade view:
This will display a list of validation errors if any exist.
6. Update the Database
Once the form is submitted, the data will be validated, updated, and saved to the database. After a successful update, you will be redirected back to the edit form with a success message.
7. Test the Update
-
Visit the edit page:
-
Modify the fields and click Update.
-
If validation passes, the record will be updated in the database, and you will see a success message.
Conclusion
-
You’ve learned how to update data in the database using Laravel 6.
-
The update process involves retrieving the record, validating the input, updating the data, and redirecting with a success message.
-
You can enhance this functionality with more complex validation and form handling based on your application’s needs.