Home > Net >  cannot find id to delete data laravel 8
cannot find id to delete data laravel 8

Time:01-20

i try to delete data using destroy() method of resource controller, but can't delete data, when i use dump and die, id can't be found, what should i do?

this is my controller:

public function destroy(User $user)
{
    User::destroy($user->id);
    return redirect('/dashboard/administrators')->with('success', 'Admin has been deleted');
}

this is my route:

Route::resource('/dashboard/administrators', DashboardAdministratorController::class)->middleware('auth');

and this is my delete form:

@foreach($users as $user)
    <tr>
        <td>{{ $loop->iteration }}</td>
        <td>{{ $user->name }}</td>
        <td>{{ $user->username }}</td>
        <td>{{ $user->email }}</td>
        <td>
        <form action="/dashboard/administrators/{{ $user->id }}" method="POST" >
              @method('delete')
              @csrf
              <button  onclick="return confirm('Are You Sure?')">Deactive</button>
               </form>
         </td>
     </tr>
@endforeach

CodePudding user response:

You using route model binding. Then you can use the Laravel delete()function.

public function destroy(User $user)
{
    $user->delete();
    return redirect('/dashboard/administrators')->with('success', 'Admin has been deleted');
}

CodePudding user response:

I already succeeded to delete data.

A solution to my problem is refactor the method to:

public function destroy($userId)
{
   User::where('id', $userId)->delete();
   return redirect('/dashboard/administrators')->with('success', 'Admin has been deleted');
}

I still don't understand why this could happen. If there anyone can explaining it, I really appreciate it.

  • Related