motinska94's avatar

findOr not working

I'm trying to delete a note but it's not going into the function I wrote in findOr. I open the notes page in 2 seperate tabs, delete the note from one tab, and trying to delete the same one again on the other tab, instead of just returning back with note_deleted = 0, it's giving me the error below the code.

public function delete(Request $request)
    {
        $note = Note::findOr($request->note_id, function(){
            return back()->with(['note_deleted' => 0]);
        });
        
        $success = 0;
        if ($note->user_id == Auth::id()){
            $success = $note->delete();
        }
        return back()->with(['note_deleted' => $success]);
    }
Undefined property: Illuminate\Http\RedirectResponse::$user_id

On this line :

if ($note->user_id == Auth::id()){

The code shouldn't even go to that line because it's supposed to return back at findOr. Because the note user trying to delete doesn't exist.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

because the return in your findOr only returns from the closure, not return from the controller.

if you want to avoid an error, catch it

    try {
        $note = Note::where('user_id',Auth::id())->findOrFail($request->note_id);

        $note->delete();

        return back()->with(['note_deleted' => true]);

    } catch(Exception $e) {
        
        return back()->with(['note_deleted' => false]);

     }

Personally I would just make like the note was deleted, whether it was or not. What can the user do about it if something goes wrong? And if they are tinkering trying to delete other's notes, dont give them any clue what's happening

Please or to participate in this conversation.