Getting the nth route parameter in a controller - laravel

I have a route defined in routes.php similar to:
Route::get('something/{firstId}/{secondId}/{thirdId}/{nthId}', 'SomeController#read')->name('read');
In my controller, I have it setup like this, which works perfectly:
public function read($firstId, $secondId, $thirdId, $nthId, Request $request){
...
}
I don't need $firstId, $secondId, etc for the particular method. I just need the $nthId. Is it possible to setup my controller so I can just grab the nth parameter and simplify my code? For example:
public function read($nthId, Request $request){
...
}

You can set argument list using variadic a preceeding ... there is an interesting caption on php.net arguments page and here is it:
Therefore in your case you would have:
public function read(Request $request, ...$ids){
$id2 = $ids[1]; //here is the second path parameter in /id1/id2/id3/..n
...
}
One thing is that variadic parameters have to be last in the declaration.
Ps: I might not be totally correct about injecting other parameters but at least with the example above, it worked correctly.

Related

Laravel: Multiple Route to Same Controller

May I know how can I make just a single route so I don't have to repeat it? Thanks in advance.
Route::get('/url', 'CtcFormController#index' )->name('CtcForm.ch');
Route::post('/url/submit', 'CtcFormController#submit')->name('CtcForm.submit');
Route::view('/url/submitted', 'form.submit')->name('CtcForm.submit');
Route::get('/url2','CtcFormController#store')->name('CtcForm.eng');
Route::post('/url2/submit', 'CtcFormController#submit')->name('CtcForm.submit');
Route::view('/url2/submitted', 'form.submit')->name('CtcForm.submit');
As per your given example, you want to handle the variable part of the route which is /url/ and /url12/. Yes! you can handle there both different route using a single route in ways:
Use route variable to handle dynamic url values i.e. url, url2,url3...url12 and so on.
Route::get('/{url}', 'CtcFormController#index' )->name('CtcForm.ch');
Route::post('/{url}/submit', 'CtcFormController#submit')->name('CtcForm.submit');
Route::view('/{url}/submitted', 'form.submit')->name('CtcForm.submit');
Now in your controller methods handing above routes receive extra parameter $url like:
In controller CtcFormController.php class:
public function index(Request $request, string $url) {
//$url will gives you value from which url request is submitted i.e. url or url12
//method logic goes here ...
}
Similarly, method handling /{url}/submit route will be like:
public function submit(Request $request, string $url) {
//method logic goes here ...
}
Let me know if you have any further query regarding this or you face any issue while implementing it.

How to route an dynamic url?

I am new to laravel. I am defining this route to an edit button:
<button class="btn btn-primary">Edit task</button>
The url is generated fine but the page is not found. I am returning a view with my TaskController#edit with this route:
Route::get('/editTasks/{{ $task->id }}', 'TaskController#edit');
Can someone help me out figuring what i am doing wrong?
When defining routes, the route parameters should only have one { around them. Also, you should not use a variable in the declaration but a name for the variable.
In your example, this could be a valid declaration:
Route::get('/editTasks/{id}', 'TaskController#edit');
More information can be found in the docs: https://laravel.com/docs/5.7/routing#route-parameters
It is also recommended to use route names, so the url can be automatically generated.
For example:
// Route declaration
Route::get('/editTasks/{id}', 'TaskController#edit')->name('tasks.edit');
// In view
Edit task
no you have to define in your route just like this :
Route::get('/editTasks/{id}', 'TaskController#edit');
you don't have $task in your route and you dont need to write any other thing in your route. in your controller you can access to this id like this :
public function edit($taskId) {
}
and only you do this
You need to use single { instead of double, so it needs to be the following in your route:
Route::get('/editTasks/{taskId}', 'TaskController#edit');
And in your edit function:
public function edit($taskId) { }
The double { in the template is correct as this indicates to retrieve a variable
Extra information/recommendation:
It is recommended to let the variable name in the route match the variable in your function definition (as shown above), so you always get the expected variable in your function. If they do not match Laravel will use indexing to resolve the variable, i.e. if you have multiple variables in your route pattern and only use one variable in the function it will take your first route parameter even if you might want the second variable.
Example:
If you have a route with the pattern /something/{var1}/something/{var2} and your function is public function test($variable2) it would use var1 instead of var2. So it it better to let these names match so you always get the expected value in your function.
It's better to use "Route Model Binding". Your route should be like this:
Route::get('/editTasks/{task}', 'TaskController#edit');
And in Controller use something like this:
public function edit($task){
}

Laravel Routes and 'Class#Method' notation - how to pass parameters in URL to method

I am new to Laravel so am uncertain of the notation. The Laravel documentation shows you can pass a parameter this way:
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
Which is very intuitive. Here is some existing coding in a project I'm undertaking, found in routes.php:
Route::get('geolocate', 'Api\CountriesController#geolocate');
# which of course will call geolocate() in that class
And here is the code I want to pass a variable to:
Route::get('feed/{identifier}', 'Api\FeedController#feed');
The question being, how do I pass $identifier to the class as:
feed($identifier)
Thanks!
Also one further sequitir question from this, how would I notate {identifier} so that it is optional, i.e. simply /feed/ would match this route?
You should first create a link which looks like:
/feed/123
Then, in your controller the method would look like this:
feed($identifier)
{
// Do something with $identifier
}
Laravel is smart enough to map router parameters to controller method arguments, which is nice!
Alternatively, you could use the Request object to return the identifier value like this:
feed()
{
Request::get('identifier');
}
Both methods have their merits, I'd personally use the first example for grabbing one or two router parameters and the second example for when I need to do more complicated things.

Laravel 5 - Unable to access the ID variable within the route

My current setup:
Controller:
public function showGeneralPage($id, ShowClinicFormRequest $request)
{
return View::make('clinic.general', ['clinic' => Clinic::where('id', $id)
->first()]);
}
ShowClinicFormRequest:
public function authorize()
{
$clinicId = $this->route('clinic');
return Clinic::where('id', $clinicId)
->where('user_id', Auth::id())
->exists();
}
Route:
Route::get('clinic/{id}/general', 'ClinicController#showGeneralPage
When trying to click through to the page - General, it presents a forbidden error.
To be honest, I'm not overly fussed on even having to show the ID based on the clinic, within the URL, but I can't see any other way around it? Any help would be hugely appreciated. Many thanks.
You may try this (I've found three problems tho):
$id = $this->route()->parameter('id'); // $this->route('id') works as well
Also you need to pass the id when generating the URI, for example:
{{ url("clinic/{$id}/general") }} // $id may have some value, i.e: 10
Also, you need to change the order of parameters here:
public function showGeneralPage($id, ShowClinicFormRequest $request)
Should be:
public function showGeneralPage(ShowClinicFormRequest $request, $id)
Note: When using Method Injection place your method parameters after the type hinted dependency injection parameters.
There are two problems here. First, you have to pass the id along when generating the URL. Assuming a variable $id:
url('clinic/'.$id.'/general')
Second, you are trying to retrieve the parameter clinic, however it is actually called id.
Change it to:
$clinicId = $this->route('id');

Call an index controller with parameter

So basically, I have a setup of restful controller in my route. Now my problem is how can I call the Index page if there is a parameter.. it gives me an error of Controller not found
Im trying to call it like this www.domain.com/sign-up/asdasdasd
Route::controller('sign-up','UserRegisterController');
then in my Controller
class UserRegisterController extends \BaseController {
protected $layout = 'layouts.unregistered';
public function getIndex( $unique_code = null )
{
$title = 'Register';
$this->layout->content = View::make( 'pages.unregistred.sign-up', compact('title', 'affiliate_ash'));
}
By registering:
Route::controller('sign-up','UserRegisterController');
You're telling the routes that every time the url starts with /sign-up/ it should look for corresponding action in UserRegisterController in verbAction convention.
Suppose you have:
http://domain.com/sign-up/social-signup
Logically it'll be mapped to UserRegister#getSocialSignup (GET verb because it is a GET request). And if there is nothing after /sign-up/ it'll look for getIndex() by default.
Now, consider your example:
http://domain.com/sign-up/asdasdasd
By the same logic, it'll try looking for UserRegister#getAsdasdasd which most likely you don't have. The problem here is there is no way of telling Route that asdasdasd is actually a parameter. At least, not with a single Route definition.
You'll have to define another route, perhaps after your Route::controller
Route::controller('sign-up','UserRegisterController');
// If above fail to find correct controller method, check the next line.
Route::get('sign-up/{param}', 'UserRegisterController#getIndex');
You need to define the parameter in the route Route::controller('sign-up/{unique_code?}','UserRegisterController');. The question mark makes it optional.
Full documentation here: http://laravel.com/docs/routing#route-parameters

Resources