0
votes

I working on laravel to build my php project . I can retrieve data from database successfully but I can not delete records when press delete button , I trying to delete record using ajax so this my ajax code

$('.userdelete').on('click', function () {
    alert('dfsfs');
    var id = $(this).data('id');
    $.ajax({
        type: 'DELETE',
        url: '/users/' + id,
        data: {
            '_token': $('input[name=_token]').val(),
        },
        success: function (data) {
            alert(data);
            toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
            $('.item' + data['id']).remove();
        },
        error: function (data) {
            console.log(data);
        }
    });
});

this is the route

Route::resource('users','radcheckController');

Users Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{
    protected $table="radcheck";
}

this is the controller's destroy function

public function destroy($id)
{
    $res = Users::where('username', $id)->delete();
}
2
What version of Laravel are you using?Rwd
you need to fix, add _method: 'delete' to data in ajaxSakezzz
Can you show us error? are you passing CSRF Token in ajax?Intekhab Khan
if you're using $id as a primary key, use User::find($id)->delete()abr
this is the error DELETE localhost:8000/users/10966417880 500 (Internal Server Error)Muh

2 Answers

0
votes

You need to specify the correct column, but you didn't pick one. Use find or findOrFail with $id or use first(). Right way is:

public function destroy($id)

{
    $res = Users::find($id);
    $res->delete();
}

or try:

public function destroy($id)
{
    $res = Users::where('username', $id)->first()->delete();
}
0
votes

Are you passing the id or the username to the end point? 'Cause on your controller you're looking for a username, the parameter is named as id, is that right?