Reputation:
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...
Upvotes: 0
Views: 4953
Reputation: 1111
Two things you can do.
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
]);
}
public function showQuestion($slug) {
$show = Question::where('slug', $slug)->first();
if(is_null($show)){
abort(404);
}
return view('questions.question',[
'show' => $show
]);
}
Upvotes: 1