본문 바로가기
iaa.dev/Laravel8

Laravel 8 관리자 화면 (Multiple Authentication) - Admin 모델 사용

by chopper.kid 2022. 1. 7.

준비작업

이전글에서 작업한 상태까지 설치되어있으면 됩니다.

 

 

Laravel 8 로그인/회원가입(Authentication) - Jetstream

Laravel 로 웹애플리케이션을 만들때 가장 기본인 유저 로그인 / 가입 등의 기능은 이미 다 준비되어 있습니다. Laravel 7 까지는 laravel/ui 를 설치하여 이용하도록 하였고 , 8 부터는 Laravel Jetstream 을

vuxy.tistory.com

Admin 모델 및 관련 마이그레이션 , 시더 , 팩토리 , 컨트롤러 , 리소스 등을 생성

php artisan make:model -a Admin

 

테이블 작성

database/migrations/날짜_create_admins_table.php 의 내용을 다음과 같이 합니다.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
}

 

모델작성

app/Models/Admin.php 의 내용을 

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use HasFactory;
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',

    ];


}

Seeder 작성 

database/seeders/AdminSeeder.php 를 

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class AdminSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Admin::create([
            'name'     => 'admin',
            'email'    => 'vuxy@test.com',
            'password' => bcrypt('password'),
        ]);
    }
}

그리고 database/seeders/DatabaseSeeder.php 에 추가

 

    public function run()
    {
        // \App\Models\User::factory(10)->create();
        $this->call([AdminSeeder::class]);
    }
}

마이그레이트 및 시딩

php artisan migrate

php artisan db:seed

 

가드 추가

config/auth.php 에 

  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        //추가
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
       ],
    ],
    
    
  'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        //추가
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],

 

Admin route 설정

routes/admin.php 작성

<?php

use Illuminate\Support\Facades\Route;

Route::get('/login',    'App\Http\Controllers\Admin\AdminLoginController@showLoginForm')->name('login');
Route::post('/login',   'App\Http\Controllers\Admin\AdminLoginController@login')->name('login.submit');
Route::get('logout/',   'App\Http\Controllers\Admin\AdminLoginController@logout')->name('logout');
Route::get('/',         'App\Http\Controllers\Admin\DashboardController@dashboard')->name('dashboard');

 

ServiceProvider에 추가 

app/Providers/RouteServiceProvider.php 수정

 

    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));

            Route::prefix('admin)
                ->middleware(['web' ])
                ->namespace($this->namespace)
                ->as('admin.)
                ->group(base_path('routes/admin.php'));

        });
    }

 

컨트롤러 작성

app/Http/Admin/AdminLoginController.php

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Auth;
use Route;

class AdminLoginController extends Controller
{

    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => ['logout']]);
    }

    public function showLoginForm()
    {
        return view('admin.admin_login');
    }

    public function login(Request $request)
    {
        // Validate the form data
        $this->validate($request, [
            'email'   => 'required|email',
            'password' => 'required|min:6'
        ]);
        // Attempt to log the user in
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
        }
        // if unsuccessful, then redirect back to the login with the form data
        return redirect()->back()->withInput($request->only('email', 'remember'));
    }

    public function logout()
    {
        Auth::guard('admin')->logout();
        return redirect('/admin');
    }
}

app/Http/Admin/Controller.php

 

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller as AdminBaseController;

class Controller extends AdminBaseController
{

    public function __construct()
    {
        $this->middleware('auth:admin');

    }

}
<?php

namespace App\Http\Controllers\Admin;

class DashboardController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function dashboard()
    {

        return view(
            "admin.dashboard" ,
            [
            ]
        );
    }
}

 

AdminLTE 설치

앞에 했던것처럼 관리화면용 패키지 설치

composer require jeroennoten/laravel-adminlte
php artisan adminlte:install

View 파일 작성

resources/views/admin/admin_login.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset=UTF-8>
  <meta name=viewport content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <title>Admin</title>
</head>
<body>
    <div class="container">

        <div class="row justify-content-center mt-4  relative flex items-top justify-center ">
          <div class="col-md-4">
            <div class="card">
              <div class="card-body">
                <form id="sign_in_adm" method="POST" action="{{ route('admin.login.submit') }}">
                  {{ csrf_field() }}
                <h1>Admin Login</h1>
                <div >
                  <input type="email" name=email class="form-control" placeholder="Email Address" value="{{ old('email') }}" required autofocus>
                </div>
                @if ($errors->has('email'))
                <span ><strong>{{ $errors->first('email') }}</strong></span>
                @endif
                <br>
                <div >
                  <input type="password" name="password" class="form-control" required>
                </div>
                <br>
                <div >
                  <button type="submit" class="btn btn-primary">Admin Login</button>
                </div>
                </form>
              </div>
            </div>
          </div>
      </div>
    </div>
</body>
</html>

resources/views/admin/dashboard.blade.php

 

@extends('adminlte::page')

@section('title', 'Dashboard')

@section('content_header')
    <h1>Dashboard</h1>
@stop

@section('content')
    <p>Welcome to this beautiful admin panel.</p>
@stop

@section('css')
    <link rel="stylesheet" href="/css/admin_custom.css">
@stop

@section('js')
    <script> console.log('Hi!'); </script>
@stop

 

https://vuxy-003.test/admin/login 

에 접속해서  ID: vuxy@test.com , PASSWORD: password

입력하면 

이쁜 관리자화면을 확인할 수 있습니다.

반응형
SMALL

댓글