CodeIgniter Laravel PHP Example HTML Javascript jQuery MORE Videos New

How to delete data from database using Laravel and Ajax


web.php

Route::POST('/userData/getUserData','UserDataController@getUserData');

Route::resource('/userData','UserDataController');

userDataController.php (controller)

public function index()
    {
            return view('userData.index');
    }
public function getUserData(){
        $userData = UserData::get();
        return json_encode(array('data'=>$userData));
    }

public function destroy($id)
    {
        UserData::find($id)->delete();
        
        return json_encode(array('statusCode'=>200));
       
    }
    

userData.php (model)

class UserData extends Model
{
    protected $table = 'users_info';
    protected $fillable = [
        'type','name', 'email','phone','city'
    ];
}
     

index.blade.php

@extends('userData.layout')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel Demo</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('userData.create') }}"> Create New User</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered table-sm">
       <thead>
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>email</th>
            <th>Phone</th>
		    <th>City</th>
            <th width="280px">Action</th>
        </tr>
       </thead>
       <tbody id="bodyData">

       </tbody>  
    </table>
      
<script>
        $(document).ready(function() {
            var url = "{{URL('userData')}}";
            $.ajax({
                url: "/userData/getUserData",
                type: "POST",
                data:{ 
                    _token:'{{ csrf_token() }}'
                },
                cache: false,
                dataType: 'json',
                success: function(dataResult){
                    console.log(dataResult);
                    var resultData = dataResult.data;
                    var bodyData = '';
                    var i=1;
                    $.each(resultData,function(index,row){
                        var editUrl = url+'/'+row.id+"/edit";
                        bodyData+="<tr>"
                        bodyData+="<td>"+ i++ +"</td><td>"+row.name+"</td><td>"+row.email+"</td><td>"+row.phone+"</td>"
                        +"<td>"+row.city+"</td><td><a class='btn btn-primary' href='"+editUrl+"'>Edit</a>" 
                        +"<button class='btn btn-danger delete' value='"+row.id+"' style='margin-left:20px;'>Delete</button></td>";
                        bodyData+="</tr>";
                        
                    })
                    $("#bodyData").append(bodyData);
                }
            });


    $(document).on("click", ".delete", function() { 
        var $ele = $(this).parent().parent();
        var id= $(this).val();
        var url = "{{URL('userData')}}";
        var dltUrl = url+"/"+id;
		$.ajax({
			url: dltUrl,
			type: "DELETE",
			cache: false,
			data:{
				_token:'{{ csrf_token() }}'
			},
			success: function(dataResult){
				var dataResult = JSON.parse(dataResult);
				if(dataResult.statusCode==200){
					$ele.fadeOut().remove();
				}
			}
		});
	});
        
});
</script>
@endsection
    

layout.blade.php

    <!DOCTYPE html>
    <html lang="{{ app()->getLocale() }}">
    <head>
        <title>LaravelDemo</title>
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <!-- Style -->
        <style>
            .input-box { position: relative; }
            .unit { position: absolute; display: block; left: 5px; top: 10px; z-index: 9; }
            .fixedTxtInput { display: block; border: 1px solid #d7d6d6; background: #fff; padding: 10px 10px 10px 30px; width: 100%; }
        </style>    
    
    </head>
    <body>
      
    <div class="container">
        @yield('content')
    </div>
       
    </body>
    </html>