Создайте модель администратора, например, в app\Models
скажем, Admin.php
. Go к вашему config\auth.php
файлу и под Аутентификационными гвардейцами сделайте что-то вроде этого
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
В том же файле под провайдерами сделайте что-то вроде этого
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
ШАГ ВТОРОЙ Откройте Authenticate.php
в папке app\Http\Middleware
и сделайте так, чтобы она выглядела примерно так
/**
* Determine if the user is logged in to any of the given guards.
*
* @param \Illuminate\Http\Request $request
* @param array $guards
* @return void
*
* @throws \Illuminate\Auth\AuthenticationException
*/
protected function authenticate($request, array $guards)
{
if (empty($guards)) {
$guards = [null];
}
foreach ($guards as $guard)
{
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
$guard = $guards[0];
if ($guard == 'admin')
{
$request->path = 'url-to-admin-login-page';
}
else
{
$request->path = '';
}
throw new AuthenticationException(
'Unauthenticated.', $guards, $this->redirectTo($request)
);
}
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string
*/
protected function redirectTo($request)
{
if (! $request->expectsJson())
{
return route($request->path.'login');
//return route('login');
}
}
STEP THREE Откройте RedirectIfAuthenticated.php
в папке app\Http\Middleware
и измените ее на
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
switch ($guard)
{
case 'admin' :
{
if (Auth::guard($guard)->check())
{
return redirect('url-to-admin-home');//the url to admin home
}
break;
}
default :
{
if (Auth::guard($guard)->check())
{
return redirect('/home');
}
break;
}
}
return $next($request);
}
ШАГ ЧЕТВЕРТЫЙ Наконец, во всех ваших классах контроллера администратора убедитесь, что в их конструкторе вы добавили охрану 'auth:admin
для их защиты. Например,
<?php
пространство имен App \ Http \ Controllers;
use App \ Http \ Controllers \ Controller; use App \ Models \ Admin;
Класс AdminController расширяет конструктор контроллера {/ ** * AdminController. * / publi c function __construct () {$ this-> middleware ('auth: admin'); }
public function index()
{
return view('admin.home');
}
}
Обращаем ваше внимание: рекомендуется закомментировать оригинальный код, а не удалять его.