Laravel 중급 태스크 목록 편집하기

경고: 로그인하지 않았습니다. 편집을 하면 IP 주소가 공개되게 됩니다. 로그인하거나 계정을 생성하면 편집자가 사용자 이름으로 기록되고, 다른 장점도 있습니다.

편집을 취소할 수 있습니다. 이 편집을 되돌리려면 아래의 바뀐 내용을 확인한 후 게시해주세요.

최신판 당신의 편집
6번째 줄: 6번째 줄:


==소개==
==소개==
이 빠른 시작 가이드는 Laravel 프레임워크에 대한 중급 소개를 제공하며, 데이터베이스 마이그레이션, Eloquent ORM, 라우팅, 인증, 인가, 의존성 주입, 유효성 검증, 뷰, Blade 템플릿에 대한 내용을 포함하고 있습니다. Laravel 프레임워크나 PHP 프레임워크에 대한 기본 지식이 있는 경우, 이 가이드를 시작하기에 적합합니다.
이 빠른 시작 가이드는 Laravel 프레임워크에 대한 중급 소개를 제공하며, 데이터베이스 마이그레이션, Eloquent ORM, 라우팅, 인증, , 의존성 주입, 검증, 뷰, Blade 템플릿에 대한 내용을 포함하고 있습니다. Laravel 프레임워크나 PHP 프레임워크에 대한 기본 지식이 있는 경우, 이 가이드를 시작하기에 적합합니다.


Laravel의 기본 기능들을 샘플로 다루어 보기 위해, 태스크들을 다루는 태스크 목록 애플리케이션을 만들어 보겠습니다. 즉, 전형적인 "할 일" 목록 예제를 다루게 됩니다. [[Laravel 초급 태스크 목록 |"초급" 빠른 시작]]과 달리, 이 튜토리얼에서는 사용자가 계정을 만들고 애플리케이션에 인증할 수 있도록 할 것입니다. 이 프로젝트의 완성된 소스코드는 [https://github.com/laravel/quickstart-intermediate GitHub에서 확인]할 수 있습니다.
Laravel의 기본 기능들을 샘플로 다루어 보기 위해, 태스크들을 다루는 태스크 목록 애플리케이션을 만들어 보겠습니다. 즉, 전형적인 "할 일" 목록 예제를 다루게 됩니다. [[Laravel 기본 태스크 목록 |"기본" 빠른 시작]]과 달리, 이 튜토리얼에서는 사용자가 계정을 만들고 애플리케이션에 인증할 수 있도록 할 것입니다. 이 프로젝트의 완성된 소스코드는 [https://github.com/laravel/quickstart-intermediate GitHub에서 확인]할 수 있습니다.


==설치==
==도커 환경==
[[Laravel Homestead|Homestead 가상머신]]을 사용하거나 선택한 로컬 PHP 환경을 사용하여 프레임워크를 실행할 수 있습니다. 여기서는 도커 기반 실습환경에서 진행합니다.
 
===도커 기반 실습환경 (선택사항)===
<syntaxhighlight lang='bash'>
mkdir ~/workspace
cd ~/workspace
docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --network host -h docker --entrypoint="" bitnami/laravel bash
</syntaxhighlight>
<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@wsl:~# mkdir ~/workspace
testuser@lcoalhost:~$ mkdir ~/workspace && cd ~/workspace
root@wsl:~# cd ~/workspace
testuser@localhost:~/workspace$ docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --entrypoint="" --network host bitnami/laravel:latest bash
root@wsl:~/workspace$ docker run --name laravel --rm -it -v ${PWD}:/workspace -w /workspace --network host -h docker --entrypoint="" bitnami/laravel bash
Unable to find image 'bitnami/laravel:latest' locally
Unable to find image 'bitnami/laravel:latest' locally
latest: Pulling from bitnami/laravel
latest: Pulling from bitnami/laravel
28번째 줄: 19번째 줄:
Digest: sha256:d16af27a0d4c2f6f3f71c730d7def97de91e0b2ea0233e84dc758340521b1629
Digest: sha256:d16af27a0d4c2f6f3f71c730d7def97de91e0b2ea0233e84dc758340521b1629
Status: Downloaded newer image for bitnami/laravel:latest
Status: Downloaded newer image for bitnami/laravel:latest
root@docker:/workspace#
root@localhost:/workspace#  
</syntaxhighlight>
</syntaxhighlight>


===Laravel 설치===
==설치==
환경이 준비되면 Composer를 사용하여 Laravel 프레임워크를 설치할 수 있습니다:
우선, Laravel 프레임워크을 새로 설치해야 합니다. [[Laravel Homestead|Homestead 가상머신]]을 사용하거나 선택한 로컬 PHP 환경을 사용하여 프레임워크를 실행할 수 있습니다. 로컬 환경이 준비되면 Composer를 사용하여 Laravel 프레임워크를 설치할 수 있습니다:


<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
39번째 줄: 30번째 줄:


<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@docker:/workspace# composer create-project laravel/laravel quickstart --prefer-dist
root@localhost:/workspace# composer create-project laravel/laravel quickstart --prefer-dist
Creating a "laravel/laravel" project at "./quickstart"
Creating a "laravel/laravel" project at "./quickstart"
Installing laravel/laravel (v11.1.1)
Installing laravel/laravel (v11.1.1)
54번째 줄: 45번째 줄:
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='console'>
<syntaxhighlight lang='console'>
root@docker:/workspace# cd quickstart/
root@localhost:/workspace# cd quickstart/
root@docker:/workspace/quickstart# find app/ routes/ resources/ | grep .php
root@localhost:/workspace/quickstart# find app/ routes/ resources/ | grep .php
app/Providers/AppServiceProvider.php
app/Providers/AppServiceProvider.php
app/Http/Controllers/Controller.php
app/Http/Controllers/Controller.php
62번째 줄: 53번째 줄:
routes/web.php
routes/web.php
resources/views/welcome.blade.php
resources/views/welcome.blade.php
</syntaxhighlight>
{{소스헤더|개발서버 실행}}
<syntaxhighlight lang='console'>
root@docker:/workspace/quickstart# php artisan serve
  INFO  Server running on [http://127.0.0.1:8000].
  Press Ctrl+C to stop the server
^C
</syntaxhighlight>
</syntaxhighlight>


'''참고''': [[composer create-project laravel/laravel quickstart --prefer-dist]]
'''참고''': [[composer create-project laravel/laravel quickstart --prefer-dist]]
[[파일:Fresh-dark.png|640px]]
===vscode 실행 (선택사항)===
<syntaxhighlight lang='console'>
root@wsl:~# code ~/workspace/quickstart/
root@wsl:~#
</syntaxhighlight>
wsl에서는 docker와 디렉토리를 공유합니다. 따라서 vscode에서 파일 편집은 가능하지만 Artisan CLI 명령어는 실행할 수 없습니다. Artisan CLI 명령어는 docker 컨테이너 내부에서 실행해야 합니다.


==데이터베이스 준비==
==데이터베이스 준비==
179번째 줄: 149번째 줄:


{{소스헤더|app/Models/Task.php}}
{{소스헤더|app/Models/Task.php}}
<syntaxhighlight lang='php' highlight='12-17'>
<syntaxhighlight lang='php'>
<?php
<?php
 
namespace App\Models;
namespace App;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model;
 
class Task extends Model
class Task extends Model
{
{
    use HasFactory;
     /**
     /**
     * The attributes that are mass assignable.
     * The attributes that are mass assignable.
216번째 줄: 183번째 줄:
먼저 <code>User</code> 모델에 <code>tasks</code> 관계를 정의해보겠습니다. Eloquent 관계는 모델의 메소드로 정의됩니다. Eloquent는 여러 가지 관계를 지원하므로 전체 Eloquent 문서를 참조하여 더 많은 정보를 확인하세요. 이 경우에는, <code>User</code> 모델에 <code>hasMany</code> 메소드를 호출하는 <code>tasks</code> 함수를 정의합니다:
먼저 <code>User</code> 모델에 <code>tasks</code> 관계를 정의해보겠습니다. Eloquent 관계는 모델의 메소드로 정의됩니다. Eloquent는 여러 가지 관계를 지원하므로 전체 Eloquent 문서를 참조하여 더 많은 정보를 확인하세요. 이 경우에는, <code>User</code> 모델에 <code>hasMany</code> 메소드를 호출하는 <code>tasks</code> 함수를 정의합니다:


{{소스헤더|app/Models/User.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='14-20'>
<?php
<?php


namespace App\Models;
namespace App;


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


class User extends Authenticatable
class User extends Authenticatable
{
{
     // Other Eloquent Properties...
     // 기타 Eloquent 속성들...
 
     /**
     /**
     * Get all of the tasks for the user.
     * 사용자의 모든 태스크를 가져옵니다.
     */
     */
     public function tasks()
     public function tasks()
244번째 줄: 207번째 줄:
다음으로, <code>Task</code> 모델에 <code>user</code> 관계를 정의해보겠습니다. 이번에도 모델에 메소드로 관계를 정의합니다. 이 경우에는, <code>belongsTo</code> 메소드를 사용하여 관계를 정의합니다:
다음으로, <code>Task</code> 모델에 <code>user</code> 관계를 정의해보겠습니다. 이번에도 모델에 메소드로 관계를 정의합니다. 이 경우에는, <code>belongsTo</code> 메소드를 사용하여 관계를 정의합니다:


{{소스헤더|app/Models/Task.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='7,20-26'>
<?php
<?php


namespace App\Models;
namespace App;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;


class Task extends Model
class Task extends Model
{
{
    use HasFactory;
     /**
     /**
     * The attributes that are mass assignable.
     * 대량 할당 가능한 속성들.
     *
     *
     * @var array
     * @var array
266번째 줄: 225번째 줄:


     /**
     /**
     * Get the user that owns the task.
     * 태스크를 소유한 사용자를 가져옵니다.
     */
     */
     public function user(): BelongsTo
     public function user()
     {
     {
         return $this->belongsTo(User::class);
         return $this->belongsTo(User::class);
278번째 줄: 237번째 줄:


==라우팅==
==라우팅==
태스크 목록 애플리케이션의 [[Laravel 초급 태스크 목록|초급 버전]]에서는 <code>routes/web.php</code> 파일 내에서 클로저를 사용하여 모든 로직을 정의했습니다. 여기서는 주로 [[Laravel 컨트롤러|컨트롤러]]를 사용하여 라우트를 조직할 것입니다. 컨트롤러를 사용하면 HTTP 요청 처리 로직을 여러 파일에 걸쳐 분산시켜 더 나은 조직화를 할 수 있습니다.
태스크 목록 애플리케이션의 [[Laravel 기본 태스크 목록|기본 버전]]에서는 <code>routes.php</code> 파일 내에서 클로저를 사용하여 모든 로직을 정의했습니다. 여기서는 주로 [[Laravel 컨트롤러|컨트롤러]]를 사용하여 라우트를 조직할 것입니다. 컨트롤러를 사용하면 HTTP 요청 처리 로직을 여러 파일에 걸쳐 분산시켜 더 나은 조직화를 할 수 있습니다.


===뷰 표시하기===
===뷰 표시하기===
<code>routes/web.php</code>에는 클로저를 구현한 단일 라우트가 하나가 이미 작성되어 있습니다. 이는 애플리케이션의 게스트를 위한 랜딩 페이지가 될 <code>/</code> 라우트입니다. 이 라우트에서는 "welcome" 페이지를 포함하는 HTML 템플릿을 렌더링합니다.
단일 라우트를 사용하여 클로저를 구현할 것입니다. 이는 애플리케이션의 게스트를 위한 랜딩 페이지가 될 <code>/</code> 라우트입니다. 그럼, <code>/</code> 라우트를 작성해 봅시다. 이 라우트에서는 "welcome" 페이지를 포함하는 HTML 템플릿을 렌더링하고자 합니다.


Laravel에서는 모든 HTML 템플릿은 <code>resources/views</code> 디렉토리에 저장되며, <code>view</code> 헬퍼를 사용하여 이 템플릿 중 하나를 라우트에서 반환할 수 있습니다:
Laravel에서는 모든 HTML 템플릿은 <code>resources/views</code> 디렉토리에 저장되며, <code>view</code> 헬퍼를 사용하여 이 템플릿 중 하나를 라우트에서 반환할 수 있습니다:


{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
Route::get('/', function () {
     return view('welcome');
     return view('welcome');
299번째 줄: 253번째 줄:


===인증===
===인증===
사용자가 계정을 만들고 애플리케이션에 로그인할 수 있도록 하는 것도 필요합니다. 일반적으로 웹 애플리케이션에 전체 인증 레이어를 구축하는 것은 번거로운 작업일 수 있습니다. 그러나 이는 매우 일반적인 요구사항입니다.
사용자가 계정을 만들고 애플리케이션에 로그인할 수 있도록 하는 것도 필요합니다. 일반적으로 웹 애플리케이션에 전체 인증 레이어를 구축하는 것은 번거로운 작업일 수 있습니다. 그러나 이는 매우 일반적인 요구사항이기 때문에, Laravel은 이 과정을 완전히 간단하게 만들려고 시도합니다.
 
====인증 라우트 설정====
<code>routes/web.php</code> 파일에 라우트를 추가합니다.
 
{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php' highlight='3,10-19'>
<?php
 
use App\Http\Controllers\AuthController;
use Illuminate\Support\Facades\Route;
 
Route::get('/', function () {
    return view('welcome');
});
 
Route::get('/login', [AuthController::class, 'showLoginForm'])->name('login');
Route::post('/login', [AuthController::class, 'login']);
Route::post('/logout', [AuthController::class, 'logout'])->name('logout');


Route::get('/register', [AuthController::class, 'showRegistrationForm'])->name('register');
먼저, Laravel 애플리케이션에 이미 포함된 <code>app/Http/Controllers/Auth/AuthController</code>가 있다는 점에 주목하세요. 이 컨트롤러는 사용자를 생성하고 인증하는 데 필요한 모든 로직을 포함하는 특별한 <code>AuthenticatesAndRegistersUsers</code> 트레이트를 사용합니다.
Route::post('/register', [AuthController::class, 'register']);


Route::middleware(['auth'])->group(function () {
;인증 라우트 및 뷰
    Route::view('/dashboard', 'dashboard');
그렇다면 우리가 해야 할 일은 무엇일까요? 등록 및 로그인 템플릿을 만들고 인증 컨트롤러를 가리키는 라우트를 정의해야 합니다. <code>make:auth</code> Artisan 명령어를 사용하여 이 모든 작업을 수행할 수 있습니다:
});
</syntaxhighlight>


====인증 컨트롤러 생성====
<syntaxhighlight lang='bash'>
<syntaxhighlight lang='bash'>
php artisan make:controller AuthController
php artisan make:auth
</syntaxhighlight>
</syntaxhighlight>


{{소스헤더|app/Http/Controllers/AuthController.php}}
'''참고''': 이러한 뷰에 대한 전체 예제를 보려면, 애플리케이션의 전체 소스코드가 [https://github.com/laravel/quickstart-basic GitHub]에 있다는 점을 기억하세요.
<syntaxhighlight lang='php' highlight='5,7,8,12-63'>
<?php


namespace App\Http\Controllers;
이제 해야 할 일은 인증 라우트를 라우트 파일에 추가하는 것입니다. 이는 <code>Route</code> 파사드에 있는 <code>auth</code> 메소드를 사용하여 등록, 로그인, 패스워드 재설정을 위한 모든 라우트를 등록하여 수행할 수 있습니다:


use App\Models\User;
<syntaxhighlight lang='php'>
use Illuminate\Http\Request;
// 인증 라우트...
use Illuminate\Support\Facades\Auth;
Route::auth();
use Illuminate\Support\Facades\Hash;
</syntaxhighlight>
 
class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }
 
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');


        if (Auth::attempt($credentials)) {
인증 라우트가 등록되면, <code>app/Http/Controllers/Auth/AuthController</code> 컨트롤러의 <code>$redirectTo</code> 속성이 '/tasks'로 설정되어 있는지 확인합니다:
            $request->session()->regenerate();
            return redirect()->intended('dashboard');
        }


        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ]);
    }
    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
    public function showRegistrationForm()
    {
        return view('auth.register');
    }
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);
        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);
        Auth::login($user);
        return redirect()->intended('dashboard');
    }
}
</syntaxhighlight>
====로그인 뷰 작성====
{{소스헤더|resources/views/auth/login.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<!DOCTYPE html>
protected $redirectTo = '/tasks';
<html>
 
<head>
    <title>Login</title>
</head>
 
<body>
    <h2>Login</h2>
 
    @if($errors->any())
    <div>
        <ul>
            @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif
 
    <form method="POST" action="{{ route('login') }}">
        @csrf
        <div>
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" required>
        </div>
 
        <div>
            <label for="password">Password:</label>
            <input type="password" name="password" id="password" required>
        </div>
 
        <div>
            <button type="submit">Login</button>
        </div>
    </form>
</body>
 
</html>
</syntaxhighlight>
</syntaxhighlight>


====회원가입 뷰 작성====
또한 <code>app/Http/Middleware/RedirectIfAuthenticated.php</code> 파일을 적절한 리다이렉트 경로로 업데이트해야 합니다:
{{소스헤더|resources/views/auth/register.blade.php}}
<syntaxhighlight lang='php'>
<!DOCTYPE html>
<html>
 
<head>
    <title>Register</title>
</head>
 
<body>
    <h2>Register</h2>


    @if($errors->any())
    <div>
        <ul>
            @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif
    <form method="POST" action="{{ route('register') }}">
        @csrf
        <div>
            <label for="name">Name:</label>
            <input type="text" name="name" id="name" value="{{ old('name') }}" required>
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email" name="email" id="email" value="{{ old('email') }}" required>
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" name="password" id="password" required>
        </div>
        <div>
            <label for="password_confirmation">Confirm Password:</label>
            <input type="password" name="password_confirmation" id="password_confirmation" required>
        </div>
        <div>
            <button type="submit">Register</button>
        </div>
    </form>
</body>
</html>
</syntaxhighlight>
====대시보드 뷰 작성====
{{소스헤더|resources/views/dashboard.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<!DOCTYPE html>
return redirect('/tasks');
<html>
 
<head>
    <title>Dashboard</title>
</head>
 
<body>
    <h2>Dashboard</h2>
    <p>Welcome, {{ Auth::user()->name }}!</p>
 
    <form method="POST" action="{{ route('logout') }}">
        @csrf
        <button type="submit">Logout</button>
    </form>
 
    <a href="{{ url('/tasks') }}">Task List</a>
</body>
 
</html>
</syntaxhighlight>
</syntaxhighlight>


529번째 줄: 291번째 줄:
php artisan make:controller TaskController
php artisan make:controller TaskController
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='console'>
$ php artisan make:controller TaskController


  INFO  Controller [app/Http/Controllers/TaskController.php] created successfull
컨트롤러가 생성되었으니, <code>app/Http/routes.php</code> 파일에 컨트롤러를 가리키는 몇 가지 라우트를 추가해 봅시다:
 
<syntaxhighlight lang='php'>
Route::get('/tasks', 'TaskController@index');
Route::post('/task', 'TaskController@store');
Route::delete('/task/{task}', 'TaskController@destroy');
</syntaxhighlight>
</syntaxhighlight>


컨트롤러가 생성되었으니, <code>routes/web.php</code> 파일에 컨트롤러를 가리키는 몇 가지 라우트를 추가해 봅시다:
;모든 태스크 라우트 인증하기
이 애플리케이션에서는 모든 태스크 라우트가 인증된 사용자만 접근할 수 있도록 하고 싶습니다. 즉, 사용자가 태스크를 생성하려면 애플리케이션에 "로그인"해야 합니다. Laravel에서는 미들웨어를 사용하여 이러한 작업을 간단하게 할 수 있습니다.


이 애플리케이션에서는 모든 태스크 라우트가 인증된 사용자만 접근할 수 있도록 하고 싶습니다. 즉, 사용자가 태스크를 생성하려면 애플리케이션에 "로그인"해야 합니다. Laravel에서는 미들웨어를 사용하여 이러한 작업을 간단하게 할 수 있습니다.
컨트롤러의 모든 액션에 대해 인증된 사용자만 접근할 수 있도록 하려면, 컨트롤러 생성자에서 <code>middleware</code> 메소드를 호출하면 됩니다. 사용가능한 모든 라우트 미들웨어는 <code>app/Http/Kernel.php</code> 파일에 정의되어 있습니다. 이 경우에는, 모든 액션에 <code>auth</code> 미들웨어를 할당하고자 합니다:


{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='4,9-11'>
<?php
<?php
 
use App\Http\Controllers\AuthController;
namespace App\Http\Controllers;
use App\Http\Controllers\TaskController;
use Illuminate\Support\Facades\Route;
use App\Http\Requests;
...
use Illuminate\Http\Request;
Route::middleware(['auth'])->group(function () {
use App\Http\Controllers\Controller;
     Route::view('/dashboard', 'dashboard');
     Route::get('/tasks', [TaskController::class, 'index']);
class TaskController extends Controller
     Route::post('/task', [TaskController::class, 'store']);
{
     Route::delete('/task/{task}', [TaskController::class, 'destroy']);
     /**
});
    * 새 컨트롤러 인스턴스를 생성합니다.
    *
    * @return void
    */
     public function __construct()
     {
        $this->middleware('auth');
     }
}
</syntaxhighlight>
</syntaxhighlight>


567번째 줄: 340번째 줄:
우리의 <code>app.blade.php</code> 뷰는 다음과 같이 생겼습니다:
우리의 <code>app.blade.php</code> 뷰는 다음과 같이 생겼습니다:


{{소스헤더|resources/views/layouts/app.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<!-- resources/views/layouts/app.blade.php -->
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<html lang="en">
 
    <head>
<head>
        <title>Laravel Quickstart - Intermediate</title>
    <title>Laravel Quickstart - Intermediate</title>
    <link rel="stylesheet" href="https://unpkg.com/bootstrap@5/dist/css/bootstrap.min.css">
        <!-- CSS And JavaScript -->
</head>
    </head>
 
<body>
    <body>
    <nav class="navbar navbar-light bg-light border-bottom">
        <div class="container">
        <div class="container-fluid">
            <nav class="navbar navbar-default">
             Task List
                <!-- Navbar Contents -->
             </nav>
         </div>
         </div>
    </nav>
 
        @yield('content')
    @yield('content')
    </body>
</body>
 
</html>
</html>
</syntaxhighlight>
</syntaxhighlight>
597번째 줄: 370번째 줄:
Bootstrap CSS 보일러플레이트 코드는 생략하고 중요한 부분에 집중하겠습니다. 애플리케이션의 전체 소스 코드는 [https://github.com/laravel/quickstart-intermediate GitHub]에서 다운로드할 수 있습니다:
Bootstrap CSS 보일러플레이트 코드는 생략하고 중요한 부분에 집중하겠습니다. 애플리케이션의 전체 소스 코드는 [https://github.com/laravel/quickstart-intermediate GitHub]에서 다운로드할 수 있습니다:


{{소스헤더|resources/views/tasks/index.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<!-- resources/views/tasks/index.blade.php -->
@extends('layouts.app')
@extends('layouts.app')
 
@section('content')
@section('content')
 
<!-- Bootstrap Boilerplate... -->
    <!-- Bootstrap Boilerplate... -->
<div class="card m-3">
    <div class="card-header">
     <div class="panel-body">
        New Task
    </div>
 
     <div class="card-body">
         <!-- Display Validation Errors -->
         <!-- Display Validation Errors -->
         @include('common.errors')
         @include('common.errors')
 
         <!-- New Task Form -->
         <!-- New Task Form -->
         <form action="{{ url('task') }}" method="POST" class="form-horizontal">
         <form action="{{ url('task') }}" method="POST" class="form-horizontal">
             {{ csrf_field() }}
             {{ csrf_field() }}
 
             <!-- Task Name -->
             <!-- Task Name -->
             <div class="mb-3">
             <div class="form-group">
                 <label for="task">Task</label>
                 <label for="task-name" class="col-sm-3 control-label">Task</label>
                 <input type="text" name="name" id="task" class="form-control">
                 <div class="col-sm-6">
                    <input type="text" name="name" id="task-name" class="form-control">
                </div>
             </div>
             </div>
 
             <!-- Add Task Button -->
             <!-- Add Task Button -->
             <button type="submit" class="btn btn-primary">
             <div class="form-group">
                Add Task
                <div class="col-sm-offset-3 col-sm-6">
             </button>
                    <button type="submit" class="btn btn-default">
                        <i class="fa fa-plus"></i> Add Task
                    </button>
                </div>
             </div>
         </form>
         </form>
     </div>
     </div>
</div>
 
    <!-- TODO: Current Tasks -->
<!-- TODO: Current Tasks -->
@endsection
@endsection
</syntaxhighlight>
</syntaxhighlight>
642번째 줄: 418번째 줄:
이제 애플리케이션을 위한 기본 레이아웃과 뷰를 정의했습니다. 다음으로, <code>TaskController</code>의 <code>index</code> 메소드에서 이 뷰를 반환하도록 하겠습니다:
이제 애플리케이션을 위한 기본 레이아웃과 뷰를 정의했습니다. 다음으로, <code>TaskController</code>의 <code>index</code> 메소드에서 이 뷰를 반환하도록 하겠습니다:


{{소스헤더|app/Http/Controllers/TaskController.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
    /**
/**
    * Display a list of all of the user's task.
* 사용자의 모든 태스크 목록을 표시합니다.
    *
*
    * @param  Request  $request
* @param  Request  $request
    * @return Response
* @return Response
    */
*/
    public function index(Request $request)
public function index(Request $request)
    {
{
        return view('tasks.index');
    return view('tasks.index');
    }
}
</syntaxhighlight>
</syntaxhighlight>


664번째 줄: 439번째 줄:
이 폼에서는 <code>name</code> 필드를 필수로 하고, <code>255</code>자 이하로 입력되도록 해야 합니다. 검증에 실패하면 사용자를 <code>/tasks</code> URL로 리디렉션하고, 이전 입력과 오류를 [[Laravel 세션|세션]]에 플래시해야 합니다.
이 폼에서는 <code>name</code> 필드를 필수로 하고, <code>255</code>자 이하로 입력되도록 해야 합니다. 검증에 실패하면 사용자를 <code>/tasks</code> URL로 리디렉션하고, 이전 입력과 오류를 [[Laravel 세션|세션]]에 플래시해야 합니다.


{{소스헤더|app/Http/Controllers/TaskController.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
    /**
/**
    * Create a new task.
* 새 태스크를 생성합니다.
    *
*
    * @param  Request  $request
* @param  Request  $request
    * @return Response
* @return Response
    */
*/
    public function store(Request $request)
public function store(Request $request)
    {
{
        $request->validate([
    $this->validate($request, [
            'name' => 'required|max:255',
        'name' => 'required|max:255',
        ]);
    ]);
 
        // Create The Task...
    // 태스크 생성...
    }
}
</syntaxhighlight>
</syntaxhighlight>


[[Laravel 초급 태스크 목록|초급 빠른 시작]]와 비교해보면, 이 검증 코드가 상당히 다르게 보일 것입니다! 컨트롤러 내에서는 기본 Laravel 컨트롤러에 포함된 <code>ValidatesRequests</code> 트레이트의 편리함을 활용할 수 있습니다. 이 트레이트는 요청과 검증 규칙 배열을 받는 간단한 <code>validate</code> 메소드를 노출합니다.
[[Laravel 기본 태스크 목록|기본 빠른 시작]]와 비교해보면, 이 검증 코드가 상당히 다르게 보일 것입니다! 컨트롤러 내에서는 기본 Laravel 컨트롤러에 포함된 <code>ValidatesRequests</code> 트레이트의 편리함을 활용할 수 있습니다. 이 트레이트는 요청과 검증 규칙 배열을 받는 간단한 <code>validate</code> 메소드를 노출합니다.


검증이 실패했는지 수동으로 확인하거나 수동으로 리디렉션할 필요도 없습니다. 주어진 규칙에 대해 검증이 실패하면, 사용자는 자동으로 원래 있던 곳으로 리디렉션되고 오류는 자동으로 세션에 플래시됩니다. 참 편리하죠!
검증이 실패했는지 수동으로 확인하거나 수동으로 리디렉션할 필요도 없습니다. 주어진 규칙에 대해 검증이 실패하면, 사용자는 자동으로 원래 있던 곳으로 리디렉션되고 오류는 자동으로 세션에 플래시됩니다. 참 편리하죠!
689번째 줄: 463번째 줄:
뷰 내에서 <code>@include('common.errors')</code> 지시어를 사용하여 폼의 검증 오류를 렌더링한 것을 기억하세요. <code>common.errors</code> 뷰는 모든 페이지에서 동일한 형식으로 검증 오류를 쉽게 표시할 수 있게 해줍니다. 이제 이 뷰의 내용을 정의해봅시다:
뷰 내에서 <code>@include('common.errors')</code> 지시어를 사용하여 폼의 검증 오류를 렌더링한 것을 기억하세요. <code>common.errors</code> 뷰는 모든 페이지에서 동일한 형식으로 검증 오류를 쉽게 표시할 수 있게 해줍니다. 이제 이 뷰의 내용을 정의해봅시다:


{{소스헤더|resources/views/common/errors.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<!-- resources/views/common/errors.blade.php -->
@if (count($errors) > 0)
@if (count($errors) > 0)
<!-- Form Error List -->
    <!-- Form Error List -->
<div class="alert alert-danger">
    <div class="alert alert-danger">
    <strong>Whoops! Something went wrong!</strong>
        <strong>Whoops! Something went wrong!</strong>
 
    <br><br>
        <br><br>
 
    <ul>
        <ul>
        @foreach ($errors->all() as $error)
            @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
                <li>{{ $error }}</li>
        @endforeach
            @endforeach
    </ul>
        </ul>
</div>
    </div>
@endif
@endif
</syntaxhighlight>
</syntaxhighlight>
714번째 줄: 489번째 줄:
Laravel의 대부분의 관계는 <code>create</code> 메소드를 노출하며, 이 메소드는 속성 배열을 받아 관련 모델의 외래 키 값을 데이터베이스에 저장하기 전에 자동으로 설정합니다. 이 경우에는, <code>create</code> 메소드는 주어진 태스크의 <code>user_id</code> 속성을 현재 인증된 사용자의 ID로 자동 설정할 것입니다. 현재 사용자를 <code>$request->user()</code>를 사용하여 접근하고 있습니다.
Laravel의 대부분의 관계는 <code>create</code> 메소드를 노출하며, 이 메소드는 속성 배열을 받아 관련 모델의 외래 키 값을 데이터베이스에 저장하기 전에 자동으로 설정합니다. 이 경우에는, <code>create</code> 메소드는 주어진 태스크의 <code>user_id</code> 속성을 현재 인증된 사용자의 ID로 자동 설정할 것입니다. 현재 사용자를 <code>$request->user()</code>를 사용하여 접근하고 있습니다.


{{소스헤더|app/Http/Controllers/TaskController.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='13-17'>
/**
    /**
* 새 태스크를 생성합니다.
    * Create a new task.
*
    *
* @param  Request  $request
    * @param  Request  $request
* @return Response
    * @return Response
*/
    */
public function store(Request $request)
    public function store(Request $request)
{
    {
    $this->validate($request, [
        $request->validate([
        'name' => 'required|max:255',
            'name' => 'required|max:255',
    ]);
        ]);
 
    $request->user()->tasks()->create([
        $request->user()->tasks()->create([
        'name' => $request->name,
            'name' => $request->name,
    ]);
        ]);
 
    return redirect('/tasks');
        return redirect('/tasks');
}
    }
</syntaxhighlight>
</syntaxhighlight>


741번째 줄: 515번째 줄:
먼저, <code>TaskController@index</code> 메소드를 수정하여 모든 기존 태스크를 뷰로 전달해야 합니다. <code>view</code> 함수는 뷰에서 사용가능한 데이터 배열을 두 번째 인수로 받아들이며, 배열의 각 키는 뷰 내에서 변수로 사용됩니다. 예를 들어, 다음과 같이 할 수 있습니다:
먼저, <code>TaskController@index</code> 메소드를 수정하여 모든 기존 태스크를 뷰로 전달해야 합니다. <code>view</code> 함수는 뷰에서 사용가능한 데이터 배열을 두 번째 인수로 받아들이며, 배열의 각 키는 뷰 내에서 변수로 사용됩니다. 예를 들어, 다음과 같이 할 수 있습니다:


{{소스헤더|app/Http/Controllers/TaskController.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='9-13'>
/**
    /**
* 사용자의 모든 태스크 목록을 표시합니다.
    * Display a list of all of the user's task.
*
    *
* @param  Request  $request
    * @param  Request  $request
* @return Response
    * @return Response
*/
    */
public function index(Request $request)
    public function index(Request $request)
{
    {
    $tasks = $request->user()->tasks()->get();
        $tasks = $request->user()->tasks()->get();
 
    return view('tasks.index', [
        return view('tasks.index', [
        'tasks' => $tasks,
            'tasks' => $tasks,
    ]);
        ]);
}
    }
</syntaxhighlight>
</syntaxhighlight>


769번째 줄: 542번째 줄:
그러면, <code>app/Repositories</code> 디렉토리를 생성하고 <code>TaskRepository</code> 클래스를 추가합시다. Laravel의 모든 <code>app</code> 폴더는 PSR-4 자동로딩 표준을 사용하여 자동으로 로드되므로, 필요한 만큼의 추가 디렉토리를 자유롭게 생성할 수 있습니다:
그러면, <code>app/Repositories</code> 디렉토리를 생성하고 <code>TaskRepository</code> 클래스를 추가합시다. Laravel의 모든 <code>app</code> 폴더는 PSR-4 자동로딩 표준을 사용하여 자동으로 로드되므로, 필요한 만큼의 추가 디렉토리를 자유롭게 생성할 수 있습니다:


{{소스헤더|app/Http/Repositories/TaskRepository.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<?php
<?php
 
namespace App\Http\Repositories;
namespace App\Repositories;
 
use App\Models\User;
use App\User;
 
class TaskRepository
class TaskRepository
{
{
     /**
     /**
     * Get all of the tasks for a given user.
     * 주어진 사용자의 모든 작업을 가져옵니다.
     *
     *
     * @param  User  $user
     * @param  User  $user
788번째 줄: 560번째 줄:
     {
     {
         return $user->tasks()
         return $user->tasks()
            ->orderBy('created_at', 'asc')
                    ->orderBy('created_at', 'asc')
            ->get();
                    ->get();
     }
     }
}
}
797번째 줄: 569번째 줄:
레포지토리가 정의되면, 단순히 <code>TaskController</code>의 생성자에서 이를 "타입 힌트"로 지정하고 <code>index</code> 라우트 내에서 활용할 수 있습니다. Laravel은 모든 컨트롤러를 해결하기 위해 컨테이너를 사용하므로, 의존성은 자동으로 컨트롤러 인스턴스에 주입될 것입니다:
레포지토리가 정의되면, 단순히 <code>TaskController</code>의 생성자에서 이를 "타입 힌트"로 지정하고 <code>index</code> 라우트 내에서 활용할 수 있습니다. Laravel은 모든 컨트롤러를 해결하기 위해 컨테이너를 사용하므로, 의존성은 자동으로 컨트롤러 인스턴스에 주입될 것입니다:


{{소스헤더|app/Http/Controllers/TaskController.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='5,10-26,36-38'>
<?php
<?php
 
namespace App\Http\Controllers;
namespace App\Http\Controllers;
 
use App\Http\Repositories\TaskRepository;
use App\Task;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Http\Request;
 
use App\Http\Controllers\Controller;
use App\Repositories\TaskRepository;
class TaskController extends Controller
class TaskController extends Controller
{
{
     /**
     /**
     * The task repository instance.
     * 태스크 리포지토리 인스턴스.
     *
     *
     * @var TaskRepository
     * @var TaskRepository
     */
     */
     protected $tasks;
     protected $tasks;
 
     /**
     /**
     * Create a new controller instance.
     * 새 컨트롤러 인스턴스를 생성합니다.
     *
     *
     * @param  TaskRepository  $tasks
     * @param  TaskRepository  $tasks
823번째 줄: 597번째 줄:
     public function __construct(TaskRepository $tasks)
     public function __construct(TaskRepository $tasks)
     {
     {
        $this->middleware('auth');
         $this->tasks = $tasks;
         $this->tasks = $tasks;
     }
     }
 
     /**
     /**
     * Display a list of all of the user's task.
     * 사용자의 모든 태스크 목록을 표시합니다.
     *
     *
     * @param  Request  $request
     * @param  Request  $request
838번째 줄: 614번째 줄:
         ]);
         ]);
     }
     }
...
}
}
</syntaxhighlight>
</syntaxhighlight>
845번째 줄: 620번째 줄:
데이터가 전달되면 <code>tasks/index.blade.php</code> 뷰에서 태스크를 테이블에 표시할 수 있습니다. <code>@foreach</code> Blade 구문을 사용하면 간결한 루프를 작성할 수 있으며, 이는 매우 빠른 순수 PHP 코드로 컴파일됩니다:
데이터가 전달되면 <code>tasks/index.blade.php</code> 뷰에서 태스크를 테이블에 표시할 수 있습니다. <code>@foreach</code> Blade 구문을 사용하면 간결한 루프를 작성할 수 있으며, 이는 매우 빠른 순수 PHP 코드로 컴파일됩니다:


{{소스헤더|resources/views/tasks/index.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='5-39'>
@extends('layouts.app')
@extends('layouts.app')
   
   
@section('content')
@section('content')
...  
    <!-- 태스크 생성 폼... -->
<!-- Current Tasks -->
@if (count($tasks) > 0)
    <!-- 현재 태스크들 -->
<div class="card m-3">
    @if (count($tasks) > 0)
    <div class="card-header">
        <div class="panel panel-default">
        Current Tasks
            <div class="panel-heading">
    </div>
                Current Tasks
 
            </div>
    <div class="card-body">
        <table class="table table-striped">
            <div class="panel-body">
 
                <table class="table table-striped task-table">
            <!-- Table Headings -->
            <thead>
                    <!-- 테이블 헤더 -->
                <th>Task</th>
                    <thead>
                <th>&nbsp;</th>
                        <th>Task</th>
            </thead>
                        <th>&nbsp;</th>
 
                    </thead>
            <!-- Table Body -->
            <tbody>
                    <!-- 테이블 바디 -->
                @foreach ($tasks as $task)
                    <tbody>
                <tr>
                        @foreach ($tasks as $task)
                    <!-- Task Name -->
                            <tr>
                    <td class="table-text">
                                <!-- 태스크 이름 -->
                        <div>{{ $task->name }}</div>
                                <td class="table-text">
                    </td>
                                    <div>{{ $task->name }}</div>
 
                                </td>
                    <td>
                        <!-- TODO: Delete Button -->
                                <td>
                    </td>
                                    <!-- TODO: 삭제 버튼 -->
                </tr>
                                </td>
                @endforeach
                            </tr>
            </tbody>
                        @endforeach
        </table>
                    </tbody>
    </div>
                </table>
</div>
            </div>
@endif
        </div>
    @endif
@endsection
@endsection
</syntaxhighlight>
</syntaxhighlight>
895번째 줄: 670번째 줄:
<code>tasks/index.blade.php</code> 뷰에 각 행에 삭제 버튼을 추가해야 할 곳에 "TODO" 메모를 남겼습니다. 이제 각 행에 작은 단일 버튼 폼을 만들어 삭제 버튼을 추가해 보겠습니다. 버튼이 클릭되면 애플리케이션에 <code>DELETE /task</code> 요청이 전송되어 <code>TaskController@destroy</code> 메소드를 트리거하게 됩니다:
<code>tasks/index.blade.php</code> 뷰에 각 행에 삭제 버튼을 추가해야 할 곳에 "TODO" 메모를 남겼습니다. 이제 각 행에 작은 단일 버튼 폼을 만들어 삭제 버튼을 추가해 보겠습니다. 버튼이 클릭되면 애플리케이션에 <code>DELETE /task</code> 요청이 전송되어 <code>TaskController@destroy</code> 메소드를 트리거하게 됩니다:


{{소스헤더|resources/views/tasks/index.blade.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php' highlight='7-17'>
<tr>
                <tr>
    <!-- 태스크 이름 -->
                    <!-- Task Name -->
    <td class="table-text">
                    <td class="table-text">
        <div>{{ $task->name }}</div>
                        <div>{{ $task->name }}</div>
    </td>
                    </td>
 
    <!-- 삭제 버튼 -->
                    <!-- Delete Button -->
    <td>
                    <td>
        <form action="{{ url('task/'.$task->id) }}" method="POST">
                        <form action="{{ url('task/'.$task->id) }}" method="POST">
            {{ csrf_field() }}
                            {{ csrf_field() }}
            {{ method_field('DELETE') }}
                            {{ method_field('DELETE') }}
 
            <button type="submit" id="delete-task-{{ $task->id }}" class="btn btn-danger">
                            <button type="submit" id="delete-task-{{ $task->id }}" class="btn btn-danger">
                <i class="fa fa-btn fa-trash"></i>Delete
                                Delete
            </button>
                            </button>
        </form>
                        </form>
    </td>
                    </td>
</tr>
                </tr>
</syntaxhighlight>
</syntaxhighlight>


929번째 줄: 703번째 줄:
이제 <code>TaskController</code>에 <code>destroy</code> 메소드를 정의할 준비가 거의 끝났습니다. 먼저, 이 라우트에 대한 라우트 선언과 컨트롤러 메소드를 다시 확인해봅시다:
이제 <code>TaskController</code>에 <code>destroy</code> 메소드를 정의할 준비가 거의 끝났습니다. 먼저, 이 라우트에 대한 라우트 선언과 컨트롤러 메소드를 다시 확인해봅시다:


{{소스헤더|routes/web.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
    Route::delete('/task/{task}', [TaskController::class, 'destroy']);
Route::delete('/task/{task}', 'TaskController@destroy');
</syntaxhighlight>
 
/**
{{소스헤더|app/Http/Controller/TaskController.php}}
* 주어진 태스크를 삭제합니다.
<syntaxhighlight lang='php' highlight='5,12-22'>
*
<?php
* @param  Request  $request
 
* @param  Task  $task
namespace App\Http\Controllers;
* @return Response
 
*/
use App\Models\Task;
public function destroy(Request $request, Task $task)
use App\Http\Repositories\TaskRepository;
use Illuminate\Http\Request;
 
class TaskController extends Controller
{
{
...
     //
     /**
    * Destroy the given task.
    *
    * @param  Request  $request
    * @param  Task  $task
    * @return Response
    */
    public function destroy(Request $request, Task $task)
    {
        //
    }
}
}
</syntaxhighlight>
</syntaxhighlight>
973번째 줄: 731번째 줄:
</syntaxhighlight>
</syntaxhighlight>


다음으로, 정책에 <code>delete</code> 메소드를 추가해보겠습니다. 이 메소드는 <code>User</code> 인스턴스와 <code>Task</code> 인스턴스를 받습니다. 메소드는 단순히 사용자의 ID가 태스크의 <code>user_id</code>와 일치하는지 확인합니다. 실제로 모든 정책 메소드는 <code>true</code> 또는 <code>false</code>를 반환해야 합니다:
다음으로, 정책에 <code>destroy</code> 메소드를 추가해보겠습니다. 이 메소드는 <code>User</code> 인스턴스와 <code>Task</code> 인스턴스를 받습니다. 메소드는 단순히 사용자의 ID가 태스크의 <code>user_id</code>와 일치하는지 확인합니다. 실제로 모든 정책 메소드는 <code>true</code> 또는 <code>false</code>를 반환해야 합니다:


{{소스헤더|app/Policies/TaskPolicy.php}}
<syntaxhighlight lang='php'>
<syntaxhighlight lang='php'>
<?php
<?php
983번째 줄: 740번째 줄:
use App\Models\User;
use App\Models\User;
use App\Models\Task;
use App\Models\Task;
use Illuminate\Auth\Access\HandlesAuthorization;


class TaskPolicy
class TaskPolicy
{
{
    use HandlesAuthorization;
     /**
     /**
     * Determine if the given user can delete the given task.
     * 주어진 사용자가 주어진 태스크를 삭제할 수 있는지 결정합니다.
     *
     *
     * @param  User  $user
     * @param  User  $user
993번째 줄: 753번째 줄:
     * @return bool
     * @return bool
     */
     */
     public function delete(User $user, Task $task)
     public function destroy(User $user, Task $task)
     {
     {
         return $user->id === $task->user_id;
         return $user->id === $task->user_id;
1,000번째 줄: 760번째 줄:
</syntaxhighlight>
</syntaxhighlight>


;액션 인가
마지막으로, <code>Task</code> 모델을 <code>TaskPolicy</code>와 연계해야 합니다. 이는 <code>app/Providers/AuthServiceProvider.php</code> 파일의 <code>$policies</code> 속성에 한 줄을 추가하여 수행할 수 있습니다. 이를 통해 Laravel은 <code>Task</code> 인스턴스에서 태스크를 인증할 때 어떤 정책을 사용할지 알 수 있습니다:
정책이 작성되었으므로, 이를 <code>destroy</code> 메소드에서 사용해 보겠습니다. 모든 Laravel 컨트롤러는 <code>Gate</code> 파사드를 통해 authorize 메소드를 호출할 수 있습니다:


<syntaxhighlight lang='php' highlight='8,13-25'>
<syntaxhighlight lang='php'>
<?php
/**
* 애플리케이션의 정책 매핑.
*
* @var array
*/
protected $policies = [
    'App\Models\Task' => 'App\Policies\TaskPolicy',
];
</syntaxhighlight>


namespace App\Http\Controllers;
;액션 인가
정책이 작성되었으므로, 이를 <code>destroy</code> 메소드에서 사용해 보겠습니다. 모든 Laravel 컨트롤러는 <code>AuthorizesRequest</code> 트레이트를 통해 노출된 authorize 메소드를 호출할 수 있습니다:


use App\Models\Task;
<syntaxhighlight lang='php'>
use App\Http\Repositories\TaskRepository;
/**
use Illuminate\Http\Request;
* 주어진 태스크를 삭제합니다.
use Illuminate\Support\Facades\Gate;
*
 
* @param  Request $request
class TaskController extends Controller
* @param  Task  $task
* @return Response
*/
public function destroy(Request $request, Task $task)
{
{
...
     $this->authorize('destroy', $task);
     /**
    * Destroy the given task.
    *
    * @param  Request  $request
    * @param  Task  $task
    * @return Response
    */
    public function destroy(Request $request, Task $task)
    {
        Gate::authorize('delete', $task);


        // Delete The Task...
    // 태스크를 삭제합니다...
    }
}
}
</syntaxhighlight>
</syntaxhighlight>
1,041번째 줄: 801번째 줄:
마지막으로, 주어진 태스크를 실제로 삭제하는 로직을 <code>destroy</code> 메소드에 추가해 보겠습니다. Eloquent의 <code>delete</code> 메소드를 사용하여 데이터베이스에서 주어진 모델 인스턴스를 삭제할 수 있습니다. 레코드가 삭제된 후, 사용자를 <code>/tasks</code> URL로 리디렉션할 것입니다:
마지막으로, 주어진 태스크를 실제로 삭제하는 로직을 <code>destroy</code> 메소드에 추가해 보겠습니다. Eloquent의 <code>delete</code> 메소드를 사용하여 데이터베이스에서 주어진 모델 인스턴스를 삭제할 수 있습니다. 레코드가 삭제된 후, 사용자를 <code>/tasks</code> URL로 리디렉션할 것입니다:


<syntaxhighlight lang='php' highlight='12-14'>
<syntaxhighlight lang='php'>
    /**
/**
    * Destroy the given task.
* 주어진 태스크를 삭제합니다.
    *
*
    * @param  Request  $request
* @param  Request  $request
    * @param  Task  $task
* @param  Task  $task
    * @return Response
* @return Response
    */
*/
    public function destroy(Request $request, Task $task)
public function destroy(Request $request, Task $task)
    {
{
        Gate::authorize('delete', $task);
    $this->authorize('destroy', $task);
 
        $task->delete();
    $task->delete();
 
        return redirect('/tasks');
    return redirect('/tasks');
    }
}
</syntaxhighlight>
</syntaxhighlight>

제타위키에서의 모든 기여는 크리에이티브 커먼즈 저작자표시-동일조건변경허락 3.0 라이선스로 배포된다는 점을 유의해 주세요(자세한 내용에 대해서는 제타위키:저작권 문서를 읽어주세요). 만약 여기에 동의하지 않는다면 문서를 저장하지 말아 주세요.
또한, 직접 작성했거나 퍼블릭 도메인과 같은 자유 문서에서 가져왔다는 것을 보증해야 합니다. 저작권이 있는 내용을 허가 없이 저장하지 마세요!

취소 편집 도움말 (새 창에서 열림)

이 문서에서 사용한 틀: