Home > Mobile >  Best practice for controller method returns based on prefix
Best practice for controller method returns based on prefix

Time:01-18

in web.php i have two routes one for admin and other one for users as below

Route::prefix('admin')->group(function () {
    Route::get('', [AdminController::class, 'index'])->name('admin');
    Route::resources(['categories' => CategoryController::class);
});

Route::resources(['categories' => CategoryController::class);

Then I have CategoryController.php that gets data from the database and returns a view:

public static function index()
{
    $categories = Category::paginate(5);

    return response()->view('categories.categories', ['categories' => $categories]);
}

I want to change the view template based on if it goes /admin/categories or it goes /categories.

I have a solution but I want to know the best practice for that for all functions in CategoryController

index, create, store, show, edit, update, and destroy.

CodePudding user response:

Your controller method should not be static

You can use Laravels dependency injector to get the request object within your controller method:

public function index($request) 
{
    if (str_starts_with($request->getPathInfo(), '/admin')) {
        // admin controller stuff
    } else {
        // regular controller stuff
    }
}

Best practice:

It's worth mentioning that this breaks something called the Single Responsibility Principle (SRP) where you're giving more than one responsibility to a method.

I would recommend that you split this logic across two controllers, and then you don't have to worry about stuff like this:

  • AdminCategoryController
  • CategoryController

CodePudding user response:

The best practice for handling different views based on the prefix of the route would be to use a conditional statement in the controller method. For example, in the index method of the CategoryController, you can use the following code:

public static function index()
{
    $categories = Category::paginate(5);

    if (request()->route()->getPrefix() === 'admin') {
        return response()->view('admin.categories.categories', ['categories' => $categories]);
    } else {
        return response()->view('categories.categories', ['categories' => $categories]);
    }
}

This checks the prefix of the current route using the request()->route()->getPrefix() method and returns the appropriate view based on the prefix. You can use this same approach for other methods in the CategoryController that need to return different views based on the prefix.

Another way you can achieve this would be to use different controllers for the /admin and / routes and move the relevant methods to the respective controllers.

  • Related