How To Delete Data From Existing Table Using Model In Laravel

admin_img Posted By Bajarangi soft , Posted On 06-09-2020

In SQl DELETE statement is used to delete existing records in a table like that in Laravel we can delete data using model names

How To Delete Data From Existing Table Using Model In Laravel

Once you have created a model and its associated database table, Now we need delete added data in existing table using model name. 
To learn more about creating model and inserting data or updating data visit our Bajarangisoft site.


 

Deleting Models

To delete a model, call the delete method on a model instance:
Example(1)
1.Create demo.blade.php to delete created data by sending specified id to controller 

<!DOCTYPE html>
<html>
<head>
    <title>Delete Data For Existing Table Using Model In Laravel</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="text-center">
        <h1>Delete Data From Existing Table Using Model In Laravel</h1>
    </div>
    <div class="well ">
        <div class="table-responsive">
            <table class="table table-bordered">
                <thead>
                <tr class="heading">
                    <th>Name</th>
                    <th>Description</th>
                    <th>Delete</th>
                </tr>
                </thead>
                <tbody>
                @foreach ($demo as $de)
                    <tr>
                        <td>{!! $de->name !!}</td>
                        <td>{!! $de->desc !!}</td>
                        <td><a href = 'Deletedemo/{{ $de->id }}'>Delete</a></td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>

    </div>
    <br>
</div>
</body>
</html>


2.Create function in controller to delete specified data which id passed by demo.blade.php

<?php
namespace App\Http\Controllers;
use App\Models\demo;
use Illuminate\Http\Request;

class demoController extends Controller
{
public function index(){
        $demo=demo::paginate(5);
        return view('demo',compact('demo'));
    }
  
public function destroy($id) {
        $demo = demo::whereId($id)->delete();
        return 'Demo deleted successfully';
    }
}

3.Create route to connect between controller and blade file

Route::get('delete-records','demoController@index');
Route::get('delete/{id}','demoController@destroy');

 

Related Post