Update data from database using Laravel framework

Update data from database using Laravel framework


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:

use App\Http\Controllers\RecordController; Route::get('/record/{id}/edit', [RecordController::class, 'edit'])->name('record.edit'); Route::put('/record/{id}', [RecordController::class, 'update'])->name('record.update');
  • 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:

php artisan make:controller RecordController

Then, modify app/Http/Controllers/RecordController.php to include the following methods:

Edit Method

public function edit($id) { // Retrieve the record from the database using the ID $record = Record::findOrFail($id); // Return the edit view with the record data return view('records.edit', compact('record')); }

Update Method

public function update(Request $request, $id) { // Validate the incoming data $validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email', 'age' => 'required|integer', ]); // Find the record by ID and update it $record = Record::findOrFail($id); $record->name = $request->input('name'); $record->email = $request->input('email'); $record->age = $request->input('age'); $record->save(); // Redirect with a success message return redirect()->route('record.edit', $id)->with('success', 'Record updated successfully!'); }
  • 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)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Record</title> </head> <body> <h1>Edit Record</h1> @if(session('success')) <p style="color: green;">{{ session('success') }}</p> @endif <form action="{{ route('record.update', $record->id) }}" method="POST"> @csrf @method('PUT') <label for="name">Name:</label> <input type="text" id="name" name="name" value="{{ old('name', $record->name) }}" required><br><br> <label for="email">Email:</label> <input type="email" id="email" name="email" value="{{ old('email', $record->email) }}" required><br><br> <label for="age">Age:</label> <input type="text" id="age" name="age" value="{{ old('age', $record->age) }}" required><br><br> <button type="submit">Update</button> </form> <a href="{{ url()->previous() }}">Go Back</a> </body> </html>

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:

$validated = $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|email', 'age' => 'required|integer', ]);

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:

@if ($errors->any()) <div> <ul> @foreach ($errors->all() as $error) <li style="color: red;">{{ $error }}</li> @endforeach </ul> </div> @endif

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

  1. Visit the edit page:

    http://127.0.0.1:8000/record/{id}/edit
  2. Modify the fields and click Update.

  3. 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.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close