Call both middleware & controller method in a route - laravel

In my route file I can call a controller method that way
$router->get('users/{id}', 'UserController#read');
And I can assign a middleware to a route that way, according to the documentation :
$app->get('admin/profile', ['middleware' => 'testMiddleware', function () {
//
}]);
But I don't understand how I can combine both.
I tried this but it didn't work :
$router->get('users/{id}', 'UserController#read', ['middleware' => 'testMiddleware']);
Any help would be appreciated

You can do it like this:
$router->get('users/{id}', 'UserController#read')->middleware('testMiddleware');
by this way the applied middle-ware will get triggered

I just had to swap parameters to make it work :
$router->get('users/{id}', ['middleware' => 'testMiddleware'], 'UserController#read');

Related

Using route actions with new laravel route syntax

I have question about syntax which I can not find an answer for.
I have code in routes file:
Route::get(
'/something/{seoString}/{someMore}',
['as' => 'my_name', 'uses' => '\my\namespace\MyController#index', 'my_route_action' => 20]
);
And I would like to rewrite it using the new syntax for calling controller
Route::get(
'/something/{seoString}/{someMore}',
[MyController#::class, 'index'] // would like to use this new syntax
);
And it works fine, but how can I add the custom route action 'my_route_action'?
I know it's possible to wrap the routes with a group and add it this way:
Route::group(['my_route_action' => 20], static function () {
Route::get(
'/something/{seoString}/{someMore}',
[MyController#::class, 'index'] // would like to use this new syntax
);
);
But that's not what I'm looking for. I don't want to be adding one group for each route just to add the route action.
So I wanted to ask if it does exist something like ->addCustomAction() or how is this supposed to be done?
Unfortunately the route action is not a thing, and probably shouldn't be. Unsure what you're actually trying to achieve with that too.
If you're passing in GET data like a bit of data, you can do it through: {variable} so the URL would become the following:
Route::get('my-route-url/{model}/get', [MyController::class, 'methodName')->name('something')->middleware(['something'])
And in your controller, you dependency inject request if you're wanting to use that too, as well as the model:
public function methodName(Request $request, Model $model)
{
dd($request->all(), $model);
}
The "as" is the the name method. Middleware is still middleware.
If you're trying to do a Key/Pair bit of data, you need to use POST request and pass it in the data, which you can access via the $request->input('keyName') method in the controller.

Laravel routing with or without parameter in a group

For my application I am trying to create a few routes entries.
One entry to initialise the application and another for AJAX requests.
So my application should hit the initialise function if I type https.test.com/app/drive but also if I want to type some additional parameters at the end something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB
The problem is that when ever I type https.test.com/drive/specificTabNameA this clashes with the fetchData get route used by my AJAX call.
How can I access the initialise function when hitting this URl https.test.com/app/drive or also hitting something like this: https:test.com/app/drive/specificTabA or https:test.com/app/drive/specificTabB?
Route::group(['prefix' => 'drive'], function () {
Route::get('', 'CustomController#initialise');
Route::get('fetchData', 'CustomController#fetchData');
});
I've done some tests, and came with the following conclusion/solution:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{param?}', 'CustomController#initialise');
});
CustomerController:
function initialise($param = null)
{
...
}
Note that by changing the order of the routes you will actually load the correct route.
When you visit /drive/fetchData it will load fetchData route
When you visit /drive/ it will load initialise route without arguments
When you visit /drive/xyz it will load initialise route with $param being xyz
Hope it helps :)
My friend I want to get your attention to Laravel docs https://laravel.com/docs/5.0/routing#route-parameters especially this one Route Parameters. You can tell router that this route can have parameter but also can not have it. Look at this example
Route::get('/{specific?}')
Now you can get this specific parameter in your Controller function after request
public function initialize (Request $request, $specific = null)
Set it default to null as this param can both be past and not, so it should have some default value.
Good luck ;)
The following should work for you:
Route::group(['prefix' => 'drive'], function () {
Route::get('fetchData', 'CustomController#fetchData');
Route::get('{path?}', 'CustomController#initialise')->where(['path' => '.*']);
});
This will allow the following path:
/drive => initialise
/drive/1 => initalize
/drive/1/2/3 => initalize
/drive/fetchData => fetchData
Adding ->where(['path' => '.*']) will route any path to initalize, e.g. /1, /1/2, /1/2/3.
If you only want to allow the path to be one level deep you can remove the where:
Route::get('{path?}', 'CustomController#initialise');

how to set common controller in group route

I am working on laravel but i have no idea about using route.
i used route group method but i have a question that can we use a common controller in group route
like
I have bunch of routes
Route::group(['prefix' => 'agent'], function(){
Route::get('pay', 'PaymentController#pay');
Route::get('pay/success', 'PaymentController#success');
Route::get('pay/failure', 'PaymentController#failure');
Route::get('credits', 'PaymentController#credits');
Route::get('checkout', 'PaymentController#checkout');
});
As you can see they all are using same route so is there any way to make this as dry as possible i know those are small route but when it goes long line then it become hard to understand i know it's kind of stupid question
is there any attribute like
Route::group(['prefix' => 'agent', 'controller' => 'PaymentController'], function(){
Route::get('pay', 'pay');
Route::get('pay/success', 'success');
Route::get('pay/failure', 'failure');
Route::get('credits', 'credits');
Route::get('checkout', 'checkout');
});
No there isn't any option to define default controller for a route group. But if you have resource routes then it defines all the sub routes by itself, though it's limited to only CRUD routes. You can do something like this if you're interested.
Route::group(['prefix' => 'agent'], function($controller = 'TestController#') {
Route::get('pay', $controller.'pay');
Route::get('pay/success', $controller.'success');
Route::get('pay/failure', $controller.'failure');
Route::get('credits', $controller.'credits');
Route::get('checkout', $controller.'checkout');
});

Call to a member function middleware() on null

I use the following middleware in routing Laravel:
Route::group(['prefix' => 'api/'], function() {
Route::resource('admin', 'adminController')->middleware('auth');
Route::resource('profile', 'profileController')->middleware('role');
});
I get this error when i call 'admin' or 'profile' path in URL
Use this
Route::prefix("/dashboard")->middleware(['first','second'])->group(function(){
});
It is because Route::resource() does not return anything. Its void. It doesn't return an object.
Laravel 5.4 - Illuminate\Routing\Router#resource
In Laravel 5.5 (in development), Route::resource() will be returning an object for fluently adding options to.
Simply reverse the order:
Route::middleware('scope:clock-in')->resource('clock', 'ClockController');
As lagbox stated:
Route::resource() does not return anything.
However middleware does.
Most likely your resource controller is not resolving to an actual controller. Some things to check
Check you actually have an adminController, and that the class name is in the correct case
Check that your controller is in the default namespace and, if not, change the controller namespace, or add a namespace attribute to your route
Check that your controller is not causing an exception on start that is being ignored resulting in you having a null controller.
In Laravel 8.x you can solve this problem with:
Route::group(['middleware' => 'auth','middleware' => 'role'], function () {
..........
});

laravel 5.1 routes groups takes only the first controller?

Route::group(['prefix' => 'api'], function () {
Route::controller(null, 'BoxController');
Route::controller(null, 'CostController');
});
This is a routed group in Laravel 5.1 the urls for the first controller is working but not for the second one 'CostController'.
If I switch the lines the first one works only. I want both controllers url to be prefixed with ...api/box/ and ...api/cost/
Examples on the internet has only one controller in the group, maybe there is another syntax?
I want the urls like : ( because I work on REST application)
api/cost
api/box
not like:
api/cost/cost
api/box/box
Why are you using null for route?
If you'll use different routes, both will work:
Route::group(['prefix' => 'api'], function () {
Route::controller('box', 'BoxController');
Route::controller('cost', 'CostController');
});
Passing null as route is one thing but the main culprit is that you are passing the same route for different controllers. The solution is to use real routes for the controllers, so. i.e. box for BoxController and cost for the other. It will work correctly then
Route::group(['prefix' => 'api'], function () {
Route::controller('box', 'BoxController');
Route::controller('cost', 'CostController');
});

Resources