How to throw 404 if user is trying to edit link that doesn't belong to him in Laravel 8

Viewed 35

I am new to Laravel and I built a Linktree clone following a Youtube video. I had many problems since I was coding in Laravel 8 and his project was in an older version of Laravel.

Now, I don't have a problem on my Local XAMPP server but on my host when I try to open edit.blade.php to edit my links it sends me to a 404 page. That is caused by this code:

public function edit(Link $link)
    {
        if ($link->user_id !== Auth::id()) {
            return abort(404);
        }

        return view('links.edit', [
            'link' => $link
        ]);
    }

I wasn't able to fix this on a host and now I am thinking if maybe there is a different approach to this code so it works on my host. I am not sure if this code is outdated or something since I am a begginer, so I would appreciate someone's help.

4 Answers

after spending some time on this I finally fixed it. The problem was in my database on a host, I had to set it up properly.

I think that you want to do something like authorization

You need to use Policy

You can find a very useful example and explain in the documentation here

You're doing a query in the if condition to check if the link was created by the logged in user. If the link is created by the logged in user then u can access this page otherwise it returns 404 page. Now if you want to make this page accessible by any authenticated user u can use

if(!Auth::user) {
   return abort(404);
}

Try changing your function to this:

public function edit(Link $link)
{
    if ($link->user_id != auth()->user()->id) {
        abort(404);
    } else {
      return view('links.edit', ['link' => $link]);
    }
}
Related