简体   繁体   中英

Laravel 8 returns 404 Not Found

I'm making a forum with Laravel 8, and basically whenever a user asks a question on this forum, it should be redirected to the question.

And I also want to make the redirection process based on the slug field of the question.

So in order to do this, I added this at the end of postForm() method:

return redirect('questions/{slug}');

And here is the route for seeing the question:

Route::get('questions/{slug}', [QuestionController::class, 'showQuestion']);

And then I coded at the Controller:

public function showQuestion($slug)
    {
        $show = Question::find($slug);

        if(is_null($show)){
            abort(404);
        }

        return view('questions.question',[
            'show' => $show
        ]);
    }

But now the problem is, when I try to add a new question, the question will successfully added but it redirects me to 404 page. And the URL also looks like this after redirection:

http://localhost:8000/questions/%7Bslug%7D

However, if I try to add a slug - that already exists in db - manually after the /questions/ , I still get the same 404 error!

So what's going wrong here? How can I properly redirect user to that route by slug of each question?

I would really appreciate if you help me out with this...

Two things you can do.

  1. You can change yours routes as below

    Route::get('questions/{question:slug}', [QuestionController::class, 'showQuestion']

in your controller you can use dependency injection as below

public function showQuestion(Question $question)
{
  
    return view('questions.question',[
        'show' => $question
    ]);
}
  1. You can change your query from find to where

public function showQuestion($slug) {

    $show = Question::where('slug', $slug)->first();

    if(is_null($show)){
        abort(404);
    }

    return view('questions.question',[
        'show' => $show
    ]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM