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!
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:
Controller:
N.B: For
POST
request, you need to sendcsrf token
via your ajax dataor you can add header parmas like this way:
Hope this will work!