500 Internal Server Error when trying to delete mysql data record using ajax in laravel 8

1.1k views Asked by At

So my friend and I are working on an admin view for user management. I wanted this view to be able to delete users by clicking a button.

The user list itself looks like this:

@section('main')
    @csrf
    <ul class="collapsible">
        @foreach($users as $user)
            <li method="POST" action="delete">
                <div class="collapsible-header">
                    <i class="material-icons">face</i>{{$user->fname}} {{$user->lname}}
                </div>
                <div class="collapsible-body" id="{{$user->id}}">
                    <p>Adresse: {{$user->address1}}, {{$user->postalcode}} {{$user->city}}</p>
                    <p>Land: {{$user->country}}</p>
                    <p>E-Mail: {{$user->email}}</p>
                    <span>Beigetreten: {{$user->created_at}}</span>
                    <br>
                    <a class="btn red waves-effect waves-light user-delete-button" href="" 
                       id="user-delete-button" data-userid="{{$user->id}}">
                        <i class="material-icons">delete</i>
                    </a>
                </div>
            </li>
        @endforeach
    </ul>
@endsection

The script in the extended dashboard.blade.php template is the following:


    <script>
        $(document).ready(function(){
            $('.collapsible').collapsible();
            $('.user-delete-button').click(function (e){
                $.ajax({
                    url: '{{route('deleteuser')}}',
                    data: {"userid": $(this).data("userid")},
                    type: 'post',
                    success: function(data)
                    {
                        console.log('deleted');
                    }
                });
            });
        });
    </script>

The UserController:

class UserController extends Controller
{
    public static function destroy($id) {
        $user = \App\Models\User::findOrFail($id);
        $user->delete();

        return redirect('/userlist');
    }
    //
}

And at last the Route in the web.php:

Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');

So now whenever I am trying to delete a user clicking the button, I get an "500 Internal Server Error" in the console.

At this point I am more than just clueless as to what I am supposed to do to make this work. The only thing I want is to delete a record and refresh the database by simply clicking a button. But currently nothing I tried worked so far.

I hope you can help me. Thanks in advance!

3

There are 3 answers

2
SOS9GS On

Maybe you were getting 500 error because your controller class was not found. You need to use full namespace. Modify your code as follows:

Route:

Route::post('/deleteuser', [App\Http\Controllers\UserController::class, 'destroy'])->name('deleteuser');

Controller:

class UserController extends Controller
{
    public static function destroy(Request $Request) {
        $id = $Request->input('userid');
        $user = \App\Models\User::findOrFail($id);
        $user->delete();

        return redirect('/userlist');
    }
    
}

N.B: For POST request, you need to send csrf token via your ajax data

data: {
   "_token": "{{ csrf_token() }}",
   "userid": $(this).data("userid")
}

or you can add header parmas like this way:

$.ajax({
    url: '{{route('deleteuser')}}',
    data: {"userid": $(this).data("userid")},
    type: 'post',
    headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
    success: function(data)
    {
        console.log('deleted');
    }
});

Hope this will work!

0
IGP On

Option 1: Add {id} parameter to your route.

Route::post('/deleteuser/{userid}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;

class UserController extends Controller
{
    public function destroy($userid) {
        $user = User::findOrFail($userid);
        $user->delete();

        return redirect('/userlist');
    }
    
}

Option 2: Use Route Model Binding in your route and controller action:

Route::post('/deleteuser/{user}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;

class UserController extends Controller
{
    public function destroy(User $user) {
        $user->delete();

        return redirect('/userlist');
    }
    
}

Option 3: Use Request object to retrieve query string

Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function destroy(Request $request) {
        $user = User::findOrFail($request->query('userid', null));
        $user->delete();

        return redirect('/userlist');
    }
    
}
3
ismail On

your must need header file in your request so use this type:'post', header