I have multiple user types in my API (admin/agent/user). These roles should do similar things but with some different conditions. To do this I created a directory for each role and putted a copy of the controller inside that folder. Now I need to route the requests to it's folder based on loggin in user type.
For example for admin and agent roles 'userController' should routed to these routes:
'user' => 'admin/userController'
'user' => 'agent/userController'
I found this solution and modified for my needs but it's not changing the final route:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Container\Container;
use Illuminate\Http\Request;
class RoleRouting
{
/**
* @var Container
*/
private $container;
public function __construct(Container $container)
{
$this->container = $container;
}
private static $ROLES = [
'admin' => [
'namespace' => 'Admin',
],
'agent' => [
'namespace' => 'Agent',
]
];
public function handle(Request $request, Closure $next)
{
$action = $request->route()->getAction();
$role = static::$ROLES[$request->user()->role()];
$namespace = $action['namespace'] . '\\' . $role['namespace'];
$action['uses'] = str_replace($action['namespace'], $namespace, $action['uses']);
$action['controller'] = str_replace($action['namespace'], $namespace, $action['controller']);
$action['namespace'] = $namespace;
$request->route()->setAction($action);
return next($request);
}
}
And this is the route:
Route::middleware(['auth:api','RoleRouting'])->group(function (){
Route::apiResources([
'user' => 'UserController',
'user_group' => 'UserGroupController'
]);
});
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire