hkguile hkguile - 6 months ago 114
PHP Question

laravel 5.2 how to pass variable to route.php from middleware?

i have a middleware, i want it to pass $role to the 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('/');
}


is there any way to do that?

My route:

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');

});

Answer

You can do something like this:

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

Then in the routes.php:

use Illuminate\Http\Request;

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