Home > Net >  How to check parameter(in route) before go to controller class in laravel8
How to check parameter(in route) before go to controller class in laravel8

Time:12-22

I have Following Routes

  1. /product/category?item=1
  2. /product/category?item=2

So,I want to check item parameter and go to specific Controller Class like this.

Route::get('/product/category', function (Request $request) {
  if($request->input('item') == 1)
      return HomeController's item1 (Function)
  else
      return HomeController's item2 (Function)
});

It is possible in Laravel8? All of the laravel document wrote directly go to controller like this.But,I want to check parameter before going to controller.

Route::get('__url', [__Controller::class, '__function']);

CodePudding user response:

You can use laravel container:

Route::get('/product/category', function (Request $request, HomeController $controller) {
  if($request->input('item') == 1)
      return $controller->item1();
  else
      return $controller->item2();
});

CodePudding user response:

You can get items as slug like below in laravel-8

Route::get('/product/category/{item}', function($slug){
    if($slug == 1):
        echo $slug;
    else:
        echo $slug;
    endif;    
});

and call controller's method like below in laravel-8

use App\Http\Controllers\HomeController;

Route::get('/product/category/{item}', function($slug, HomeController $controller){
    if($slug == 1):
        return $controller->item1();
    else:
        return $controller->item2();        
    endif;    
});
  • Related