mercredi 31 juillet 2019

Routing to controllers in a different directory for each Role in Laravel

I have multiple user types in my API (admin/agent/user). These roles should do similar thing but with some different conditions. To do this I created a directory for each role and putted it's controllers inside that folder. Now I need to route them based on loggin in user type.

I found this solution but it's not changing the 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