user9277271
user9277271

Reputation:

Laravel 8: Getting 404 “Not Found” Page While Trying To Delete User

I'm getting all users information at Blade, like this:

@foreach($users as $user)
    <tr class="gradeX">
        <td><a href="/admin/users/user/{{ $user->name }}">{{ $user->name }}</a></td>
        <td>{{ $user->email }}</td>
        <td>{{ $user->role->name }}</td>
        <td class="actions">
        <a href="{{ route('users.edit', $user->id) }}" class="on-default edit-row" title="Edit User"><i class="fa fa-pencil"></i></a>
        <form method="POST" action="{{ route('users.destroy', $user->id) }}">
        @csrf
        @method('DELETE')
        <button class="on-default remove-row btn-svg" title="Delete User"><i class="fa fa-trash-o"></i></button>
         </form>
        </td>
    </tr>
@endforeach

As you can see, for deleting a custom user, I've added this:

<form method="POST" action="{{ route('users.destroy', $user->id) }}">
        @csrf
        @method('DELETE')
        <button class="on-default remove-row btn-svg" title="Delete User"><i class="fa fa-trash-o"></i></button>
</form>

And at destroy method of the Controller:

public function destroy($id)
    {
        $user = User::findOrFail($id);
        $photo = Photo::findOrFail($user->photo_id);
        unlink(public_path() . $user->photo->path);
        $photo->delete();
        $user->delete();

        return redirect('admin/users');
    }

But now, whenever I try to delete the user from blade, I get 404 Not Found page. However the user still exists at the DB.

And when I add dd($id); at the Controller, I get this as result:

enter image description here

And user 14 exists at the table users just like below:

enter image description here

So what is going wrong here? How can I solve this issue and delete the user properly?

I would really appreciate any idea or suggestion from any of you guys...

Thanks in advance.

Upvotes: 0

Views: 166

Answers (1)

Perry
Perry

Reputation: 11710

There are 2 options left what can be wrong, either you can’t find the user. Or you can’t find the photo. Based on the provided information it think there is no photo. The method findOrFail will return a 404 when the model is not found, see also https://laravel.com/docs/8.x/eloquent#not-found-exceptions.

So what you can do is add a dd before the photo check to see if the user is found. If that is true you can be sure it is the photo model. If that is the case, you should use Photo::find($user->photo_id).

After that you can wrap your unlink in an if statement where you Check if the photo model is not empty

public function destroy($id)
{
   $user = User::findOrFail($id);
   $photo = Photo::find($user->photo_id);
   if (!empty($photo)) {
     unlink(public_path() . $user->photo->path);
     $photo->delete();
   }
   $user->delete();

   return redirect('admin/users');
}

Upvotes: 1

Related Questions