laravel 5.2如何从中间件传递变量到route.php?

时间:2016-05-20 02:42:03

标签: php laravel laravel-5.2

我有一个中间件,我希望它将$ role传递给route.php

public function handle($request, Closure $next)
{
    if ($this->auth->check())
    {

        $role= "normal";
        $user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
        ->where('user_id', $this->auth->user()->id)->select('roles.is_admin', 'roles.is_vendor')->get();
        foreach($user_roles as $item)
        {
            //var_dump($item->is_vendor);
            //die();
            if($item->is_admin==1)
            {
                $role = "admin";
            }
            if($item->is_vendor==1)
            {
                $role = "vendor";
            }
        }
        if($role=="normal"){
            return $this->response->redirectTo('/');
        }
        //$request->attributes->add(['admin' => $admin, 'vendor' => $vendor]);
        $request->attributes->add(['role' => $role]);
        View::share ('role', $role);

        return $next($request);
    }
    return $this->response->redirectTo('/');
}

有没有办法做到这一点?

我的路线:

Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function() {
    Route::auth();
    Route::pattern('id', '[0-9]+');
    Route::pattern('id2', '[0-9]+');

    #Admin Dashboard
    Route::get('dashboard', 'Admin\DashboardController@index');

    Route::get('vendor/{id}/edit', 'Admin\VendorController@getEdit');
    Route::post('vendor/{id}/edit', 'Admin\VendorController@postEdit'); 

});

1 个答案:

答案 0 :(得分:1)

您可以这样做:

// In your middleware
$request->offsetSet('role', $role);

然后在routes.php中:

use Illuminate\Http\Request;

Route::get('test', ['middleware' => 'auth', function(Request $request) {
    dd($request->get('role')); 
}]);