Home > Blockchain >  Same route different controllers
Same route different controllers

Time:04-27

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?

CodePudding user response:

There is no way to inform the system that the given id in route is either of category or slug

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');

So modify it to add a prefix of id type like

Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('category/{category}', [App\Http\Controllers\QuestionController::class, 'index'])->name('category.list');

Route::get('slug/{slug}', [App\Http\Controllers\QuestionController::class, 'show'])->name('questions.show');

It will be looks like

Domain.com/category/1
Domain.com/slug/1

CodePudding user response:

I'd suggest to use one controller action for both slug types which determines what needs to be done, and forwards the request to the respective controller action.

https://symfony.com/doc/current/controller/forwarding.html

CodePudding user response:

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');
    }

    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'));
}
  • Related