In laravel, if I want to pass parameters to a controller in my route file
Route::get('user/sk/{id}' , '[email protected]');
If I want to pass default parameters:
Route::get('user/{name?}', function ($name = 'John') {
// how do I invoke my controller here?
return $name;
});
How do I merge the two things? Is there a shortcut?
Route::get('user/sk/{id}' , '[email protected]'
// can I add an array of default parameters here?
);
As far as I know, there is no shortcut, unfortunately.
To inject one optional parameter:
Route::get('user/{name?}', function ($name = 'John') {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk($name);
});
To inject one optional parameter with more parameters:
Assuming you had an $id
param and that [email protected]
accepts $id
and $name
.
Route::get('user/{id}/{name?}', function ($id, $name = 'John') {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk($id, $name);
});
To inject something in the controller from the router:
Assuming want to use a url as a switch.
Route::get('my-special-url', function () {
$ctrl = new \App\Http\Controllers\UsersController();
return $ctrl->findsk(1, 'Paul');
});
You can pass as a default parameter to function in your controller like just normal function
Route::get('user/sk/{id}' , '[email protected]');
in UsersController
function findsk($id ='myVal'){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With