Skip to content

Instantly share code, notes, and snippets.

@Jimmylet
Last active July 12, 2019 20:10
Show Gist options
  • Select an option

  • Save Jimmylet/6fa54d25f4a3b557750e54178febe0ab to your computer and use it in GitHub Desktop.

Select an option

Save Jimmylet/6fa54d25f4a3b557750e54178febe0ab to your computer and use it in GitHub Desktop.
Route::get('users', 'UserController@index')->middleware('role:admin,');
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Role
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
public function handle($request, Closure $next, ... $roles)
{
$user = Auth::user();
//dd($roles[$role]);
foreach ($roles as $role) {
// Check if user has the role This check will depend on how your roles are set up
if ($user->role == $role) {
return $next($request);
}
}
return response()->json(['error' => 'Unauthorized'], 403);
}
}
/*...*/
protected $routeMiddleware = [
/******/
'role' => \App\Http\Middleware\Role::class,
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment