Missing or incorrect slug check Laravel 7

Viewed 154

I'm approaching Laravel 7 recently, I was wondering how to make the script more navigable and safe. In particular, I need to redirect the visitor in a basic page in case he enters a post with a missing or incorrect slug.

**localhost/post/my-test-slug** = ok

**localhost/post/** = missing slug, redirect to index

etc, I have already tried the isset / empty controller but I don't understand why it doesn't work. How can I solve it?

public function show($slug)
    {

        $post = DB::table('post')->where('slug', $slug)->first();
        return view('show', ['post' => $post]);
    }
1 Answers

You can do this by redirecting on page 404 if the user has no slug value like one example below:

public function show($slug)
{
    if($slug == null){
      abort(404);
    }

    $post = DB::table('post')->where('slug', $slug)->first();

    if($post == null){
      abort(404);
    }

    return view('show', ['post' => $post]);
}

This is not an accurate answer but yes you use this logic in the page controller which detects route parameters and if not found then redirect it into page 404. So the exceptional will be handled.

Related