How to delete data from database using Eloquent Modal

In this post, you will be learning about how to delete data from database using Eloquent Model in Laravel 8, where we will fetch the data in html table and create one simple Delete button with <a> tag and specifing the url or path to delete data with the following routes.

So guys, Lets get started.

Before starting, as we completed Creating of Laravel 8 Project, Database Connectivity, Insert data, Fetch data & Edit and Update data in laravel and now Lets start with Deleting the data.

Step 1: add below html table <tr> with <a> tag in your fetched record table as follows:

<td>
    <a href="{{ url('delete-student/'.$item->id}}" class="btn btn-danger btn-sm">Delete</a>
</td>

Step 2: Create a route in the following path routes/web.php as follows:

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StudentController;

Route::delete('delete-student/{id}', [StudentController::class'destroy']);

Step 3: To delete the data, paste the below code in Controller as we created in app/Http/Controllers/StudentController.php

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function destroy($id)
    {
        $student = Student::find($id);
        $student->delete();
        return redirect()->back()->with('status','Student Deleted Successfully');
    }
}


That's it guys.

Thanks for reading... 


© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT