라라벨 설치 및 세팅 법 > IT 기술백서

라라벨 설치

[code]

composer create-project laravel/laravel myapp

[/code]

 

.env 파일에서 디비설정 수정

[code]

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=디비명

DB_USERNAME=아이디

DB_PASSWORD=비밀번호

[/code]

 

테이블 생성

[code]

php artisan migrate

[/code]

breeze 인증 스케폴딩 설치

[code]

composer require laravel/breeze –dev

[/code]

node 모듈 설치

[code]

npm install

[/code]

assets 컴파일

[code]

npm run dev

[/code]

  아래와 같이 에러가 날 경우

  sh: mix: command not found

  이 명령어 실행 후 다시 실행

  npm install laravel-mix@latest

  npm clean-install

 

— 이하는 개인적인 세팅 —

 

회원테이블에 필드 추가

[code]

php artisan make:migration add_column_users –table=users

[/code]

/database/migrations/xxxx_xx_xx_xxxxxx_add_column_users

[code]

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class AddColumnUsers extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::table(‘users’, function (Blueprint $table) {

            $table->foreignId(‘role_id’)->nullable()->constrained(‘roles’)->onDelete(‘set null’);

            $table->string(‘phone’, 20)->nullable()->comment(‘전화번호’);

            $table->string(‘zipcode’, 10)->nullable()->comment(‘우편번호’);

            $table->string(‘address’)->nullable()->comment(‘주소’);

            $table->string(‘address_extra’, 255)->nullable()->comment(‘참고주소’);

            $table->string(‘address_detail’)->nullable()->comment(‘상세주소’);

            $table->boolean(‘ban’)->default(false)->comment(‘로그인차단’);

            $table->timestamp(‘ban_at’)->nullable()->comment(‘차단날짜’);

            $table->text(‘memo’)->nullable()->comment(‘메모’);

        });

    }

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::table(‘users’, function (Blueprint $table) {

            $table->dropColumn(‘role_id’);

            $table->dropColumn(‘phone’);

            $table->dropColumn(‘zipcode’);

            $table->dropColumn(‘address’);

            $table->dropColumn(‘address_extra’);

            $table->dropColumn(‘address_detail’);

            $table->dropColumn(‘ban’);

            $table->dropColumn(‘ban_at’);

            $table->dropColumn(‘memo’);

        });

    }

}

[/code] 

[code]

php artisan migrate

[/code]

 

roles 마이그레이션 파일 생성

[code]

php artisan make:migration create_table_roles –create=roles

[/code]

/database/migrations/xxxx_xx_xx_xxxxxx_create_table_roles.php

[code]

public function up()

{

    Schema::create(‘roles’, function (Blueprint $table) {

        $table->id();

        $table->string(‘rid’, 40)->comment(‘아이디’);

        $table->string(‘rname’, 60)->comment(‘이름’);

        $table->text(‘section’)->comment(‘접근권한’);

        $table->timestamps();

    });

}

[/code]

[code]

php artisan migrate

[/code]

 

관리자 미들웨어 생성

[code]

php artisan make:middleware Admin

[/code]

 

관리자 미들웨어 편집

[code]

<?php

namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

class Admin

{

    /**

     * Handle an incoming request.

     *

     * @param  \Illuminate\Http\Request  $request

     * @param  \Closure  $next

     * @return mixed

     */

    public function handle(Request $request, Closure $next)

    {

        // 로그인 했는지 체크

        if (!Auth::check()) {

            session([‘url.intended’ => url()->current()]);

            return redirect(‘login’);

        }

        // role 이 있는지 체크 (role 에 등록된 유저는 관리자)

        if (!Auth::user()->role) {

            return redirect(route(‘home’));

        }

        return $next($request);

    }

[/code]

미들웨어 등록

app/Http/Kernel.php

[code]

protected $routeMiddleware = [

    ….

    ‘admin’ => \App\Http\Middleware\Admin::class,

]

[/code]

 

관리자 라우터 편집

[code]

Route::prefix(‘admin’)->middleware([‘admin’])->group(

    function () {

        Route::get(‘/’, [AdminDashboardController::class, ‘index’])->name(‘admin’)->breadcrumbs(fn (Trail $trail) => $trail->push(‘HOME’, route(‘admin’)));

        // 회원관리

        Route::prefix(‘user’)->group(

            function () {

                Route::get(‘/’, [UserManageController::class, ‘index’])

                        ->name(‘admin-user’)

                        ->breadcrumbs(fn (Trail $trail) => $trail->parent(‘admin’)->push(‘회원관리’, route(‘admin-user’)));

                Route::get(‘/create’, [UserManageController::class, ‘create’])

                        ->name(‘admin-user-create’)

                        ->breadcrumbs(fn (Trail $trail) => $trail->parent(‘admin-user’)->push(‘새로등록’, route(‘admin-user-create’)));

                Route::post(‘/create’, [UserManageController::class, ‘store’])->name(‘admin-user-store’);

                Route::get(‘/edit/{id}’, [UserManageController::class, ‘edit’])

                        ->name(‘admin-user-edit’)

                        ->breadcrumbs(

                            fn (Trail $trail, $id) => $trail->parent(‘admin-user’)->push(‘정보수정’, route(‘admin-user-edit’, $id))

                        );

                Route::post(‘/update/{id}’, [UserManageController::class, ‘update’])->name(‘admin-user-update’);

                Route::post(‘/delete’, [UserManageController::class, ‘delete’])->name(‘admin-user-delete’);

                Route::get(‘/ban/{id}’, [UserManageController::class, ‘ban’])->name(‘admin-user-ban’);

                Route::get(‘/unban/{id}’, [UserManageController::class, ‘unban’])->name(‘admin-user-unban’);

            }

        );

    }

    // ….

}

[/code] 

 

role을 정의할 관리자 Policy 파일 만들기

[code]

php artisan make:policy AdminPolicy

[/code] 

 

/app/Policies/AdminPolicy.php

[code]

namespace App\Policies;

use App\Models\User;

use Illuminate\Auth\Access\HandlesAuthorization;

class AdminPolicy

{

    use HandlesAuthorization;

    private $user;

    /**

     * Create a new policy instance.

     *

     * @return void

     */

    public function __construct()

    {

        //

    }

    // 실제 메소드는 없고 여기서 다 처리함

    public function __call($key, $arguments)

    {

        $user = $arguments[0];

        return $this->checkRole($user, $key);

    }

    // Role 체크

    private function checkRole($user, $key)

    {

        if ($user->role === null) {

            return false;

        }

        $key = strtolower($key);

        $sections = array_map(‘trim’, explode(‘|’, $user->role->section));

        return ($user->role->name === ‘super’ || in_array($key, $sections));

    }

}

[/code]

 

AdminPolicy 등록

/app/Providers/AuthServiceProvider.php

[code]

public function boot()

{

    $this->registerPolicies();

 

    // 관리자 메뉴별로 정책연결 (상황에 맞게 수정/추가 해야 함)

    Gate::define(‘dashboard’, [AdminPolicy::class, ‘dashboard’]);

    Gate::define(‘category’, [AdminPolicy::class, ‘category’]);

    Gate::define(‘post’, [AdminPolicy::class, ‘post’]);

    Gate::define(‘general-setting’, [AdminPolicy::class, ‘generalSetting’]);

    Gate::define(‘user’, [AdminPolicy::class, ‘user’]);

    Gate::define(‘role’, [AdminPolicy::class, ‘role’]);

     // …

}

[/code]

 

관리자 대시보드 컨트롤러 생성

[code]

php artisan make:controller Admin/AdminDashboardController

[/code]

 

/app/Http/Controllers/Admin/AdminDashboardController.php

[code]

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Gate;

class AdminDashboardController extends Controller

{

    public function index()

    {

        $this->authorize(‘dashboard’);  // Role::authrize(): role 사용 예

        return view(‘admin.dashboard’);

    }

}

[/code]

 

대시보드 view 만들기

: layouts.admin 은 첨부파일 참조

/views/admin/dashboard.blade.php

[code]

@extends(‘layouts.admin’)

@section(‘title’, ‘대시보드’)

@section(‘content’)

    <div>관리자</div>

@endsection

[/code]

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

위로 스크롤