mercredi 4 avril 2018

Passing parameters to controller method from route in Laravel 5.5

I want to pass a parameter from my route to a controller method, to avoid duplication of code. For example, I could have my routes like this

Route::get('used-cars',          array('uses' => 
'CarController@indexUsed'));
Route::get('new-cars',           array('uses' => 
'CarController@indexNew'));
Route::get('new-and-used-cars',  array('uses' => 
'CarController@indexNewAndUsed'));

and then have specific code for in each method for retrieving that car type. However, I would like to just have one index method in the controller, with a variable passed to it to indicate if it is a new or used car.

For example:

Route::get('used-cars',          array('uses' => 
'CarController@index(1)'));
Route::get('new-cars',           array('uses' => 
'CarController@index(2)'));
Route::get('new-and-used-cars',  array('uses' => 
'CarController@index(3)'));

In previous versions of Laravel I believe this could be achieved using something like this

Route::get('/used-cars', array('as' => 'used-cars', function(){
    return App::make('CarsController')->index(1);
}));

However I understand this was removed in Laravel 5.4. When I try it I only get class not found for the controller.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire