Better way to add route class under the same group - laravel-5

I am using Laravel 5.4
Route Service Provider code is below
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/Login.php'));
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/Register.php'));
Is there any way to write both route files under the same group?
Something like this...
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/Login.php'))
->group(base_path('routes/Register.php'));
In 5.3. we could write like this...
Route::group([
'middleware' => 'auth:api',
'namespace' => $this->namespace,
'prefix' => 'api/v1',
], function ($router) {
require base_path('routes/API/Driver/Driver.php');
require base_path('routes/API/Vehicle/Vehicle.php');
});

You can use the same solution as in 5.3 in 5.4
Route::group(['prefix' => 'api', /* .... */], function () {
// extract this to external files as needed
Route::get('/path', 'HomeController#method');
});

The group method takes a function as argument, so it should just be
Route::prefix('api/v1')
->middleware('api')
->namespace($this->namespace)
->group(function ($router) {
require base_path('routes/API/Driver/Driver.php');
require base_path('routes/API/Vehicle/Vehicle.php');
});
// routes/API/Driver/Driver.php
<?php
Route::get('/drivers', 'DriverController#method');
// (Route URI is '/api/v1/drivers');

Related

How to call ApiResource with middleware in my routes?

When I use middleware like below, no problem:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
But if I try to use it with apiResources, like below:
Route::apiResources([
'user' => 'API\UserController',
'posts' => 'API\PostController'
])->middleware('auth:api');
Then I get an error message:
php artisan route:list
BadMethodCallException
Method Illuminate\Routing\RouteRegistrar::apiResources does not
exist.
What is the correct way to call ApiResource with middleware in routes/api.php ?
I don't believe you can add any middleware's to the apiResources, what you could do instead is nest them inside a route group that applies them
Route::group(['middleware' => 'auth:api'], function () {
Route::apiResources([
'user' => 'API\UserController',
'posts' => 'API\PostController'
]);
});
This would also allow you to shorten the controller definitions with the namespace option:
Route::group(['middleware' => 'auth:api', 'namespace' => 'API'], function () {
Route::apiResources([
'user' => 'UserController',
'posts' => 'PostController'
]);
});

Laravel add custom middleware to route group

in my web application i have admin panel and i'm trying to make access to users that they have admin role by this code:
namespace App\Http\Middleware;
use Closure;
class CheckUserAdminRole
{
public function handle($request, Closure $next)
{
if (auth()->check()) {
if (auth()->check() && !auth()->user()->hasRole('admin')) {
auth()->logout();
return redirect(route('system.messages','userIsNotAdmin'));
}
}
return $next($request);
}
}
and in my routs i have this route group:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web'], 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
$this->get('panel', 'AdminController#index');
});
my kernel:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
...
\App\Http\Middleware\CheckUserAdminRole::class,
];
now when i add my middleware as CheckUserAdminRole to route group like with this code:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','CheckUserAdminRole'], 'prefix' => 'dashboard'], function () {
i get this error:
Class CheckUserAdminRole does not exist
this codes couldn't resolve my problem:
php artisan route:clear
php artisan cache:clear
php artisan config:clear
composer dump-autoload
Instead of registering your middleware in the $middleware array, you should register it in $routeMiddleware like so:
protected $routeMiddleware = [
...
'checkAdmin' => \App\Http\Middleware\CheckUserAdminRole::class,
];
Note: registering a middlware in the $middleware array results in it being executed for every request and therefore is not applicable on specific routes.
Then you can use it in your routes with the checkAdmin name:
Route::group(['namespace' => 'Dashboard', 'middleware' => ['auth:web','checkAdmin'], 'prefix' => 'dashboard'], function () {
Source
You can also use middleware and route group together easily like so:
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function()
{
//All the routes that belongs to the group goes here
Route::get('dashboard', function() {} );
});
Here's a simple fix without touching the Kernel file and taking advantage of the Policy. The accessAdmin is a function created inside Policy file.
Route::group(['namespace' => 'Dashboard', 'middleware' => 'can:accessAdmin, App\User', 'prefix' => 'dashboard'], function () {
$this->group(['prefix' => 'administrator'], function () {
$this->get('panel', 'AdminController#index');
});
You can try middleware with prefix and groups.
Route::middleware(['Auth'])->prefix('api/')->group(function() {
Route::group(['prefix' => 'review/'], function () {
Route::get('/', 'User\Controllers\Api\UserController#getUserReviews');
});
});
Hope its helps

Laravel apply middleware "only", "except" options to Route groups

The only reason I want to apply middleware options to my routes and not the controllers themselves is because I would like to build route groups from the same routes PHP file like the following, and I would like to do something like so:
Route::prefix('api')
->middleware('api')
->middleware('auth:api', ['only' => ['store', 'edit', 'delete']])
->middleware('auth:api', ['except' => ['index', 'show']])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::prefix('web')
->middleware('api')
->middleware('auth', ['only' => ['store', 'edit', 'delete']])
->middleware('auth', ['except' => ['index', 'show']])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
However, obviously, the official documentation listed you can have multiple middlewares with this method in routes:
route->middleware('middleware1', 'middleware2')
Is there anyway to apply the "only these methods" and "except these methods" to route groups? If no, is there another way to go around this problem within my controllers, so that they know which route group the request is from and use different middlewares accordingly?
If I understand your question correctly, route groups (as suggested in the comments) are the "official" way to do what you're describing, particularly if you nest them.
Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where conditions are merged while names, namespaces, and prefixes are appended. Namespace delimiters and slashes in URI prefixes are automatically added where appropriate.
You can also supply an array of options to the group method:
// routes/api.php
$namespaces = [
'namespace1',
'namespace2',
'namespace3',
...
];
foreach ($namespaces as $namespace) {
Route::group(['namespace' => $namespace], function() {
Route::group([
'prefix' => 'api',
'middleware' => [
'api',
['auth:api', ['only' => ['store', 'edit', 'delete']]],
['auth:api', ['except' => ['index', 'show']]]
],
], function() {
// api controller methods here
});
Route::group([
'prefix' => 'web',
'middleware' => [
'api',
['auth', ['only' => ['store', 'edit', 'delete']]],
['auth', ['except' => ['index', 'show']]]
],
], function() {
// web controller methods here
});
});
}
Note however that you may need to rearrange the array order to get the desired effect:
Middleware are executed in the order they are listed in the array

Remove web middleware in laravel 5.2

I know web middleware group is assigned to every route now. But can someone tell me how to remove if for specefic route? I tried:
class HomeController extends Controller{
public function __construct(){
$this->middleware('web',['except'=>[
'index',
]]);
}
}
And it doesn't work.
Web middleware is now applied to all routes in routes.php. This happens in the RouteServiceProvider map function.
If you have an api for example which should not use web middleware you can go with something like this
public function map(Router $router)
{
$this->mapWebRoutes($router);
$this->mapApiRoutes($router);
}
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
protected function mapApiRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'api',
], function ($router) {
require app_path('Http/routes-api.php');
});
}
Now every route in routes.php has web middleware and everything in routes-api.php the api middleware

Laravel 5.2 - Route authentication

I create the auth class from laravel and now i would like to know how i can put the /register page only for users who login in system?
my routes are:
Route::group(['middleware' => ['web']], function () {
//
Route::get('/', 'Auth\AuthController#getLogin');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
//Route::get('/register', 'Auth\AuthController#getRegister');
});
For authenticate url just add a auth middleware, that will work after logged in a user. Follow the code below:
Route::group(['middleware' => ['web','auth']], function () {
Route::get('/register', 'YourController#getRegister');
});
You have to use a middleware to filter the users.
In the case of authentication, there is a built-in middleware
called 'auth'
You can filter by middlewares in group as AnowarCst showed you
or in single routes like this:
Route::get('/register', [
'middleware' => 'auth',
'yourController#yourFunction'
]);
Read the docs to better understand
MIDDLEWARE.
Don't be scared, it's more simple than how it looks. :)
I solved the problem with this:
public function __construct()
{
$this->middleware('guest', ['except' => ['logout', 'register', 'showRegistrationForm']]);
$this->middleware('auth', ['only' => ['register', 'showRegistrationForm']]);
}
And my routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'Auth\AuthController#getLogin');
});
Route::group(['middleware' => 'web'], function () {
Route::Auth();
Route::get('/dashboard', 'HomeController#index');
});
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/register', 'Auth\AuthController#showRegistrationForm');
});
Thanks guys.

Resources