Optional route parameters not working in Lumen 5.7 - php

I had defined my route and controller as following
$router->group(['prefix' => 'api/v1'], function ($router) {
$router->group(
['middleware' => 'auth'], function() use ($router) {
$router->get('/order/get-order-status/{order_id}[/{account_id}]'
, [
'uses' => 'Api\V1\OrderController#getOrderStatus'
, 'as' => 'getOrderStatus'
]
);
});
});
following is the function defination
public function getOrderStatus($orderId, $accountId = false)
{
// my code goes here
}
Here the problem is whenever, I skip the optional account_id from the route, then passed order_id is assigned to the 2nd parameter of the function i,e. accountId. If I pass both params then everything is working as expected. I'm just confused whether something is wrong in my configuration or Lumen itself have some issue with optional route params?
Consider I had triggered http://localhost/lumen/api/v1/order/get-order-status/ORD1234 then ORD1234 is assigned to accountId and '0' is assigned to orderId

optional route parameters are given like below,
$router->get('/order/get-order-status/{order_id}/{account_id?}' // see the ? mark
though I am not sure why 0 is assigned to the orderId,
and usually, the first parameter to the controller method is a request object, so you can easily identify what are the things that the request contains.
public function getOrderStatus(Request $reqeust, $orderId, $accountId = false)

move out your optional parameter route outside the group
$router->group(['prefix' => 'api/v1'], function ($router) {
$router->get('/order/get-order-status/{order_id}[/{account_id}]'
, [
,'middleware' => 'auth',
'uses' => 'Api\V1\OrderController#getOrderStatus'
, 'as' => 'getOrderStatus'
]
);
or like this following code
$router->get('api/v1/order/get-order-status/{order_id}[/{account_id}]',
['uses' => 'Api\V1\OrderController#getOrderStatus',
'middleware' => 'auth',
'as' => 'getOrderStatus'
]
);

I think you should use optional parameter like
{account_id?} rather then [/{account_id}]

Related

Admin route group with prefix, middleware and named routes

I have some named routes in a controller named VehicleController:
vehicle.index
vehicle.show
And then I have an admin section, where I have defined a route group with prefix and middleware. In this section I have a resource controller name AdminVehicleController to handle CRUD tasks for the Vehicle (not sure if this is best practice) with the following routes:
vehicle.index
vehicle.create
vehicle.store
...
However these named routes are conflicting. My routes web.php looks like this for now:
Route::get('vehicles', 'VehicleController#index')->name('vehicle.index');
Route::get('vehicle/{vehicle}', 'VehicleController#show')->name('vehicle.show');
Route::group(['prefix' => 'admin', 'middleware' => 'is.admin'], function () {
Route::get('/', 'AdminDashboardController#index');
Route::resource('vehicle', 'AdminVehicleController');
});
If I add 'name' => 'admin' to the Route::group() array, the route names will be adminvehicle.index and not admin.vehicle.index.
What is the correct way to combine all these parameters in the route?
Try to use as parameter for your admin group
Route::group(['prefix' => 'admin', 'middleware' => 'is.admin', 'as'=> 'admin.'], function () {
Route::get('/', 'AdminDashboardController#index')->name('dashboard');
Route::resource('vehicle', 'AdminVehicleController');
});
Reference Link
Supply a names array as part of the third parameter $options array, with each key being the resource controller method (index, store, edit, etc.), and the value being the name you want to give the route.
Route::resource('vehicle', 'AdminVehicleController', [
'names' => [
'index' => 'admin.vehicle.index',
// etc...
]
]);

generate route for routes defined inside group

I have this route defined inside a group
Route::group(['domain' => '{subdomain}.test.com'], function () {
Route::get('/models/{id?}', [
'as' => 'car-model',
'uses' => 'CarModelController#details'
]);
});
I want to avoid hardcoding URLs in blade
{{route('car-model', 'ford', '100) }}
but that returs this url
ford.test.com/models
no model id!
Not sure if is relevant but in my controller CarModelController.php
I defined
public function details($subdomain, $id)
why is not sending the id to the generated url? Do I need to send the $subdomain parameter to the detail function?
I found that
{{route('car-model', ['make' => 'ford', 'id' => '100]) }}
works! thanks for watching :)

Laravel Add Post Route to Resource Route

I have a Laravel 5.2 app that is using Resource routes. I have one as follows:
Route::resource('submissions', 'SubmissionsController');
I want to add a new Post route to it for a sorting form on my index page.
Route::post('submissions', [
'as' => 'submissions.index',
'uses' => 'SubmissionsController#index'
]);
I have placed the Post route above my Resource route in my routes.php.
However, a validation Request named SubmissionRequest that is meant for forms within the Submission Resource is being executed on my new Post route. Here is my SubmissionsController Method.
public function index(SortRequest $req)
{
$submission = new Submission;
$submission = $submission->join('mcd_forms', 'mcd_forms.submission_id', '=', 'submissions.id')->where('user_id', Auth::user()->id);
$data['sort_types'] = [
'name' => 'Name',
'form_type' => 'Type'
];
$data['direction'] = ( !empty($req['asc']) ? 'asc' : 'desc' );
$data['dataVal'] = ( !empty($req['sort_type']) ? $req['sort_type'] : 'submissions.id' );
$submission->whereNull('submissions.deleted_at')->orderBy(
$data['dataVal'],
$data['direction']
);
$data['submissions'] = $submission->get();
return view('submissions.index')->with($data);
}
So, when submitting the sorting form from my index page, it is running the SubmissionRequest validation even though I am specifically calling the SortRequest validation. What am I doing wrong?
I resolved it.
Since my Post route was conflicting with my Get route for submissions.index I added below the Resource route the following:
Route::match(['get', 'post'], 'submissions', [
'as' => 'submissions.index',
'uses' => 'SubmissionsController#index'
]);
This allows the route to accept both Get and Post requests by overriding the automatically generated one.
The documentation is here: https://laravel.com/docs/master/routing#basic-routing
Route::match(['get', 'post'], 'submissions', [
'as' => 'submissions.index',
'uses' => 'SubmissionsController#index'
]);
in laravel 5 its conflict with #store action

Access a URL Parameter in a Route Prefix from Middleware

I am struggling to access a route prefix parameter from my middleware.
Given this URL: http://www.example.com/api/v1/campaign/40/status, and the following route:
Route::group( [
'prefix' => 'api/v1'
], function()
{
Route::group( [
'prefix' => 'campaign/{campaign}',
'where' => [ 'campaign' => '[0-9]+' ],
'middleware' => [
'inject_campaign'
]
], function()
{
Route::get( 'status', 'CampaignController#getStatus' );
} );
} );
How do I access the campaign parameter (40 in the example URL) from my inject_campaign middleware? I have the middleware running fine but cannot work out how to access the parameter.
Calling $request->segments() in my middleware gives me the parts of the route but this seems a fragile way of accessing the data. What if the route changes?
You can do it using shorter syntax
You can use:
echo $request->route()->campaign;
or even shorter:
echo $request->campaign;
Got it!
$request->route()->getParameter('campaign')

Laravel - Get route name in filter

How can I get current route name in filter? I tried use Route::currentRouteName(); but it's null.
Route::filter('belongsToUser', function(){
dd( Route::currentRouteName() );
exit;
});
Route looks for example:
Route::get('/openTicket/{id}', array('before' => 'auth|belongsToUser', 'uses' => 'MyController#MyAction'));
Your route isn't named, so it's no surprise the route name is null. You need an as parameter.
Route::get('/openTicket/{id}', array(
'as' => 'yourRouteName',
'before' => 'auth|belongsToUser',
'uses' => 'MyController#MyAction'));
http://laravel.com/docs/routing#named-routes

Categories