im trying to use same route but different controllers, but not getting a clean and good solution for it, for example my intention is:
Domain.com/category-slug
Domain.com/article-slug
But each one have different controller, using the same structure routes doesnt go to the intended controller, above leave my web.php
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/{category}', [App\Http\Controllers\QuestionController::class, 'index'])->name('category.list');
Route::get('/{slug}', [App\Http\Controllers\QuestionController::class, 'show'])->name('questions.show');
Does someone got the same situation and how it handle it?
As Laravel said in this situation is the second route will never be visited because the first one will overwrite it So, I only suggest that you can check over the coming category
if it does not match any category in your database then redirect the request to the next route because it will high probability to match any record in the Article
model or FINALLY abort the request if no data returned.
public function index($category)
{
$data = \App\Models\Category::where('name', $category)->get();
if (empty($data)) {
return redirect()->route('questions.show', $category);
}
return view('index', compact('data'));
}
public function show($article)
{
$data = \App\Models\Article::where('name', $article)->get();
if (empty($data)) {
abort(404, "NOT FOUND");
}
return view('show', compact('data'));
}