You can accomplish this by creating a middleware that checks if the user is authenticated and has the correct role. If they don't, you can redirect them to the appropriate route.
First, create a middleware that checks if the user is authenticated and has the correct role:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->hasRole('admin')) {
return $next($request);
}
return redirect('/home');
}
}
Then, register the middleware in your app/Http/Kernel.php file:
protected $routeMiddleware = [
// ...
'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Finally, add the middleware to the /admin route in your routes/web.php file:
Route::get('/admin', 'AdminController@index')->middleware('admin');
Now, when an unauthenticated user or a user without the correct role tries to access the /admin route, they will be redirected to /home.