タイトル: クイックスタート & チュートリアル(中級者向け)
この本文には実行可能なタグ等が含まれるため、安全のためHTMLソースとして表示しています。本文データは変更していません。
<table border="1" cellpadding="1" cellspacing="1" style="width:1000px">
<thead>
<tr><th style="background-color:#f39c12;color:#ffffff;text-align:left">この記事の要点</th></tr>
</thead>
<tbody>
<tr>
<td style="background-color:#fef9e7">
<ul>
<li>Laravel の<strong>クイックスタート&チュートリアル</strong>(中級者向け)</li>
<li>対象: DB / Eloquent / ルーティング / 認証 / コントローラ / ビュー / バリデーション / DI / Blade</li>
<li>前提: Laravel 導入済 + Windows なら XAMPP 導入済</li>
<li>小さな TODO アプリを通じて主要機能を一通り体験する</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>当記事では<strong>Laravel</strong>を使用して<strong>Webアプリケーションを作成</strong>します。</p>
<p>アプリの作成を通してLaravelの以下の項目を説明します。</p>
<p>・データベース<br />
・Eloqunetモデル<br />
・Eloquentリレーション<br />
・ルーティング<br />
・認証<br />
・コントローラー<br />
・ビュー<br />
・バリデーション<br />
・依存注入<br />
・認可<br />
・Bladeテンプレート</p>
<p>※Laravelの導入が済んでいない場合は<a href="https://jpn.itlibra.com/article?id=10857">こちら</a>を参照。</p>
<p>※Windowsクライアントの方はXAMPPを使用するのでXAMPPの導入が済んでいない場合は<a href="https://jpn.itlibra.com/article?id=10339">こちら</a>を参照。</p>
<p> </p>
<h2>インストール</h2>
<p>「<strong><span style="color:#000000">quickstart</span></strong>」という名前のプロジェクトを新規に作成しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">composer </span><span style="color:#f1c40f">create-project</span><span style="color:#ffffff"> laravel/laravel quickstart --prefer-dist</span></td>
</tr>
</tbody>
</table>
<p> </p>
<h2>データベースの準備</h2>
<p><strong>■データベースの作成(Windowsクライアントの場合)</strong></p>
<p><strong>XAMPP</strong>のControl Panelから<strong>phpMyAdmin</strong>を起動しましょう。</p>
<p><img alt="" src="/uploadImage/20180322003236_1796658.png" /></p>
<p><strong>phpMyAdmin</strong>を開いたら「<strong>New</strong>」ボタンを押して「<strong>test</strong>」データーベースを作成しましょう。</p>
<p> </p>
<p><strong>■データベースの作成(Linux / Mac クライアントの場合)</strong></p>
<p>ターミナルで以下のコマンドを実行します。</p>
<table style="border:undefined; width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">sudo get mysql-server</span></p>
<p><span style="color:#ffffff">sudo get php-mysqlnd</span></p>
<p><span style="color:#ffffff">sudo mysql -u root</span></p>
<p><span style="color:#ffffff">create database test;</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>■ユーザーの作成</strong></p>
<p>「test」データベースを選択した状態で以下のコマンドを実行してデーターベースユーザーを作成しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">GRANT ALL PRIVILEGES <br />
ON test.* <br />
TO testUser@localhost <br />
IDENTIFIED BY 'testPass';</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>■データーベースの接続設定</strong></p>
<p>Laravel内にあるデータベースの接続設定を変更します。</p>
<p>ルートフォルダ直下の「.env」ファイルの以下の部分を変更しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">DB_CONNECTION=mysql<br />
DB_HOST=127.0.0.1<br />
DB_PORT=3306<br />
DB_DATABASE=test<br />
DB_USERNAME=testUser<br />
DB_PASSWORD=testPass</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p><strong>■テーブルの作成</strong></p>
<p>データベースのマイグレーション機能を用いてテーブルを作成してみましょう。</p>
<p>今回は「<strong>user</strong>」と「<strong>task</strong>」テーブルを使用します。</p>
<p> </p>
<p>「<strong>user</strong>」はLaravelインストール時にデフォルトで定義されています。</p>
<p>「<strong>task</strong>」テーブルを作成しましょう。</p>
<p> </p>
<p>ルートディレクトリに移動して以下のコマンドを実行します。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">make:migration</span><span style="color:#ffffff"> create_tasks_table --create=tasks</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p>「<strong>database\migrations</strong>」配下にファイルが新規作成されたことを確認できます。</p>
<p>ファイルの中身を見てみましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">public function up()<br />
{<br />
Schema::</span><span style="color:#f1c40f">create</span><span style="color:#ffffff">('tasks', function (Blueprint $table) {<br />
$table->increments('id');<br />
$table->timestamps();<br />
});<br />
}</span></td>
</tr>
</tbody>
</table>
<p>これはデフォルトの定義です。</p>
<p>このファイルを編集し、タスクの名前を保存するstringカラムと、tasksとusersテーブルを結びつけるuser_idカラムを追加しましょう。</p>
<p>以下の様にテーブル定義を変えます。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">public function up()<br />
{<br />
Schema::create('tasks', function (Blueprint $table) {<br />
$table->increments('id');</span><br />
<span style="color:#f1c40f"> $table->integer('user_id')->unsigned()->index();<br />
$table->string('name');</span><br />
<span style="color:#ffffff"> $table->timestamps();<br />
});<br />
}</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p>ファイルを書き換えただけではテーブルの構造は変化しません。</p>
<p>ファイルを保存して以下のコマンドを実行しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">migrate</span></td>
</tr>
</tbody>
</table>
<p>※デフォルトのテーブルでkey関連のエラーが発生した場合は「<strong>database\migrations</strong>」配下にある該当テーブルファイルの「->unique()」や「->index()」の記述を削除するか、もしくは以下のように対象のカラムのモジコードを変更しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">$table->string('email')->charset('utf8')->unique();</span></td>
</tr>
</tbody>
</table>
<p> </p>
<h2>Eloqunetモデル</h2>
<p>次にDBからデータの保存、取得をする際に利用する<strong>Eloqunet</strong>というORMを作成しましょう。</p>
<blockquote>
<p>※「ORM(O/R Mapping)」とは</p>
<p>O/Rは「Object/Relational」の略で、オブジェクトとリレーショナルデータベースのデータの間をマッピングする技術のこと。</p>
</blockquote>
<p> </p>
<p>「<strong>user</strong>」と「<strong>task</strong>」のモデルを使用しますが、「<strong>user</strong>」はデフォルトで作成されています。</p>
<p>以下のコマンドを実行して「<strong>Task</strong>」というモデルを作成します。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">make:model</span><span style="color:#ffffff"> Task</span></td>
</tr>
</tbody>
</table>
<p>モデルとなるクラスは、指定した名前でプロジェクトの「<strong>app</strong>」フォルダ内に作成されるので確認しましょう。</p>
<p> </p>
<p><strong>【Task.php】の中身</strong></p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff"><?php</span>
<p><span style="color:#ffffff">namespace App;</span></p>
<p><span style="color:#ffffff">use Illuminate\Database\Eloquent\Model;</span></p>
<p><span style="color:#ffffff">class Task </span><span style="color:#f1c40f">extends Model</span><br />
<span style="color:#ffffff">{<br />
//<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>モデルに対して代入ができるようname属性を登録します。</p>
<p>以下の様に内容を書き変えておきましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App;</span></p>
<p><span style="color:#ffffff">use Illuminate\Database\Eloquent\Model;</span></p>
<p><span style="color:#ffffff">class Task extends Model<br />
{<br />
/**<br />
* 複数代入を行う属性<br />
*<br />
* @var array<br />
*/<br />
protected </span><span style="color:#f1c40f">$fillable</span><span style="color:#ffffff"> = ['name'];<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>Eloqunetリレーション</h2>
<p>「<strong>User</strong>」と「<strong>Task</strong>」のデータの紐づけを行います。</p>
<p>「<strong>User</strong>」と「<strong>Task</strong>」は<span style="color:#e74c3c">1対多の関係</span>にします。</p>
<p> </p>
<p>まず「<strong>User</strong>」の定義に以下の内容を追記します。(※黄色い部分)</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App;</span></p>
<p><span style="color:#ffffff">use Illuminate\Foundation\Auth\User as Authenticatable;</span></p>
<p><span style="color:#ffffff">class User extends Authenticatable<br />
{<br />
/**<br />
* The attributes that are mass assignable.<br />
*<br />
* @var array<br />
*/<br />
protected $fillable = [<br />
'name', 'email', 'password',<br />
];</span></p>
<p><span style="color:#ffffff"> /**<br />
* The attributes that should be hidden for arrays.<br />
*<br />
* @var array<br />
*/<br />
protected $hidden = [<br />
'password', 'remember_token',<br />
];<br />
</span><br />
<span style="color:#f1c40f"> /**<br />
* 特定ユーザーの全タスク取得<br />
*/<br />
public function tasks()<br />
{<br />
return $this->hasMany(Task::class);<br />
}</span><br />
<span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>まず「<strong>Task</strong>」の定義を以下のように書き換えます。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App;</span></p>
<p><span style="color:#ffffff">use App\User;<br />
use Illuminate\Database\Eloquent\Model;</span></p>
<p><span style="color:#ffffff">class Task extends Model<br />
{<br />
/**<br />
* 複数代入する属性<br />
*<br />
* @var array<br />
*/<br />
protected $fillable = ['name'];</span></p>
<p><span style="color:#ffffff"> /**<br />
* タスク所有ユーザーの取得<br />
*/<br />
public function user()<br />
{<br />
return $this-></span><span style="color:#f1c40f">belongsTo</span><span style="color:#ffffff">(User::class);<br />
}<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>ルーティング</h2>
<p><strong>ルーティング</strong>とはコントローラとURLを対応させる仕組みです。</p>
<p>※コントローラーについては後述。</p>
<p> </p>
<p>「<strong>app/Http/routes.php</strong>」のファイルにルーティングの定義をします。</p>
<p><span style="color:#e74c3c">※Laravel5.3以降は、「<strong>routes</strong>」フォルダ配下にある「<strong>web.php</strong>」がそれに該当します。</span></p>
<p>「<strong>app/Http/routes.php</strong>」もしくは「<strong>routes/web.php</strong>」の内容を確認してみましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff"><?php</span>
<p><span style="color:#ffffff">Route::get('/', function () {<br />
return view('welcome');<br />
});</span></p>
</td>
</tr>
</tbody>
</table>
<p>「<strong>/</strong>」にアクセスすると「<strong>welcome</strong>」ビューを表示するという意味です。</p>
<p> </p>
<h2>認証</h2>
<p>Laravelでログイン認証システムを実装しましょう。</p>
<p>認証には「<strong>app/Http/Controllers/Auth/AuthController</strong>」を使用します。</p>
<p><span style="color:#e74c3c">※Laravel5.?以降は、「<strong>app/Http/Controllers/Auth/</strong>」フォルダ配下にあるファイル群がそれに該当します。</span></p>
<p> </p>
<p>ユーザー登録/ログイン画面はコマンドで一括で作成することが出来ます。</p>
<p>以下のコマンドを実行しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">make:auth</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p>「<strong>app/Http/routes.php</strong>」もしくは「<strong>routes/web.php</strong>」の内容を確認してみましょう。</p>
<p>下記の内容が追記されています。</p>
<p>※追記されていない、もしくは違う記述の場合は対応するLaravelのバージョンのドキュメントを参照してください。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">Auth::routes();</span>
<p><span style="color:#ffffff">Route::get('/home', 'HomeController@index')->name('home');</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>認証画面を開いてみましょう。</p>
<p>ルートディレクトリ上で以下のコマンドを実行してサーバーを起動します。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">serve</span></td>
</tr>
</tbody>
</table>
<p> </p>
<p>「<strong>http://localhost:8000/login</strong>」にアクセスしてみましょう。</p>
<p>認証画面が開かれます。</p>
<p><img alt="" src="/uploadImage/20180325021729_5357967.png" /></p>
<p> </p>
<h2>コントローラー</h2>
<p>「<strong>app/Http/Controllers</strong>」に新しいコントローラーを作成しましょう。</p>
<p>今回作成するのはタスクコントローラーです。</p>
<p>以下のコマンドを実行します。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">make:controller</span><span style="color:#ffffff"> TaskController</span></td>
</tr>
</tbody>
</table>
<p>「<span style="color:#000000"><strong>TaskController</strong></span>」の中身は空です。</p>
<p> </p>
<p>「<strong>app/Http/routes.php</strong>」もしくは「<strong>routes/web.php</strong>」に「<span style="color:#000000"><strong>TaskController</strong></span>」を実行する記述をします。</p>
<p>とりあえず以下の実装をしておきましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff">Route::get('/tasks', 'TaskController@index');<br />
Route::post('/task', 'TaskController@store');<br />
Route::delete('/task/{task}', 'TaskController@destroy');</span></td>
</tr>
</tbody>
</table>
<p> </p>
<h2>ルートの認証化</h2>
<p>タスク関連のページはログインしていなければアクセス出来ない仕様にします。</p>
<p>「<strong>app/Http/Controllers/</strong><span style="color:#000000"><strong>TaskController</strong></span>」に以下の記述をしましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App\Http\Controllers;</span></p>
<p><span style="color:#ffffff">use App\Http\Requests;<br />
use Illuminate\Http\Request;<br />
use App\Http\Controllers\Controller;</span></p>
<p><span style="color:#ffffff">class TaskController extends Controller<br />
{<br />
/**<br />
* 新しいコントローラインスタンスの生成<br />
*<br />
* @return void<br />
*/<br />
public function __construct()<br />
{<br />
$this-></span><span style="color:#f1c40f">middleware('auth')</span><span style="color:#ffffff">;<br />
}<br />
}</span></p>
<p> </p>
</td>
</tr>
</tbody>
</table>
<p>「<span style="color:#e74c3c"><strong>middleware('auth')</strong></span>」とすることで要認証と出来ます。</p>
<p> </p>
<h2>ビューについて</h2>
<p>Laravelのビューは「<strong>resources/views</strong>」に保管します。</p>
<p>例えば「<span style="color:#e74c3c"><strong>return view('welcome');</strong></span>」と定義したのは「<strong>resources/views/welcome.blade.php</strong>」を表示するということです。</p>
<p>↓が今回作るビューの完成形です。(※今回CSSはいじらないのであくまでイメージです)</p>
<p><img alt="" src="/uploadImage/20180322095921_4834714.png" /></p>
<p> </p>
<h2>レイアウトの作成</h2>
<p>Laravelは<span style="color:#e74c3c"><strong>Bladeテンプレート</strong></span>を使用することでページ間の特徴を共有できます。</p>
<p>今回はレイアウトを「<strong>resources/views/layouts/app.blade.php</strong>」として定義します。</p>
<p>「<strong>.blade.php</strong>」拡張子とすることで<strong>Bladeテンプレートエンジン</strong>をするとフレームワークに指示を出します。</p>
<p>「<strong>resources/views/layouts/app.blade.php</strong>」を確認しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><!DOCTYPE html><br />
<html lang="{{ app()->getLocale() }}"><br />
<head><br />
~~略~~<br />
</head><br />
<body><br />
<div id="app"><br />
~~略~~<br />
<main class="py-4"><br />
</span><span style="color:#f1c40f">@yield('content')</span><br />
<span style="color:#ffffff"> </main><br />
</div><br />
</body><br />
</html></span><br />
</p>
</td>
</tr>
</tbody>
</table>
<p>「<span style="color:#e74c3c"><strong>@yield('content')</strong></span>」は「<strong>contentセクション</strong>」を持つ子ビューを挿入するという意味です。</p>
<p> </p>
<h2>子ビューの作成</h2>
<p>それでは「<strong>contentセクション</strong>」を持つ子ビューを作成しましょう。</p>
<p>※先ほど作ったのは<strong>レイアウト</strong>で今回は<strong>ビュー</strong>です。</p>
<p> </p>
<p>「<strong>TaskController</strong>」の<strong>index</strong>メソッドに対応する「<strong>resources/<span style="color:#000000">views/tasks/index.blade.php</span></strong>」を定義します。</p>
<p>※CSSは省きます</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><!-- resources/views/tasks/index.blade.php --></span></p>
<p><span style="color:#f1c40f">@extends('layouts.app')</span></p>
<p><span style="color:#f1c40f">@section('content')</span></p>
<p><span style="color:#ffffff"> <!-- Bootstrapの定形コード… --></span></p>
<p><span style="color:#ffffff"> <div class="panel-body"><br />
<!-- バリデーションエラーの表示 --><br />
</span><span style="color:#f1c40f">@include('common.errors')</span></p>
<p><span style="color:#ffffff"> <!-- 新タスクフォーム --><br />
<form action="{{ url('task') }}" method="POST" class="form-horizontal"><br />
{{ csrf_field() }}</span></p>
<p><span style="color:#ffffff"> <!-- タスク名 --><br />
<div class="form-group"><br />
<label for="task-name" class="col-sm-3 control-label">Task</label></span></p>
<p><span style="color:#ffffff"> <div class="col-sm-6"><br />
<input type="text" name="name" id="task-name" class="form-control"><br />
</div><br />
</div></span></p>
<p><span style="color:#ffffff"> <!-- タスク追加ボタン --><br />
<div class="form-group"><br />
<div class="col-sm-offset-3 col-sm-6"><br />
<button type="submit" class="btn btn-default"><br />
<i class="fa fa-plus"></i> Add Task<br />
</button><br />
</div><br />
</div><br />
</form><br />
</div></span></p>
<p><span style="color:#ffffff"> <!-- TODO: Current Tasks --></span><br />
<span style="color:#f1c40f">@endsection</span></p>
</td>
</tr>
</tbody>
</table>
<p>「<strong>@extends('layouts.app')</strong>」は先ほど作成した「<strong>resources/views/layouts/app.blade.php</strong>」レイアウトを使用するという意味です。</p>
<p>「<span style="color:#000000"><strong>@section('content')</strong></span>」から「<span style="color:#000000"><strong>@endsection</strong></span>」の内容を、先ほどのレイアウトで定義した「<span style="color:#e74c3c"><strong>@yield('content')</strong></span>」の部分に挿入します。</p>
<p>「<strong>@include('common.errors')</strong>」は「<strong>resources/views/common/errors.blade.php</strong>」のテンプレートを使用するという意味です。</p>
<p>(このテンプレートは後ほど作成します。)</p>
<p> </p>
<p>「<strong>TaskController</strong>」に以下の<strong>index</strong>メソッドを定義してこのビューを返すようにしましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* ユーザーの全タスクをリスト表示<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function index(Request $request)<br />
{<br />
return </span><span style="color:#f1c40f">view('tasks.index')</span><span style="color:#ffffff">;<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>バリデーション(入力値チェック)</h2>
<p>子ビューの入力値をチェックする処理を実装します。</p>
<p>値の追加はPOSTメソッドで行います。新たに「<strong>TaskController@store</strong>」を追加します。</p>
<p>このフォームでは、nameフィールドの入力が必須で、内容が255文字以下であることを確認します。</p>
<p>バリデーションに失敗したら、ユーザを「<strong>/tasks</strong>」のURLへリダイレクトし、同時に以前の入力とエラーをsessionへフラッシュデータとして保存するようにします。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* 新タスク作成<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function store(Request $request)<br />
{<br />
$this-></span><span style="color:#f1c40f">validate</span><span style="color:#ffffff">($request, [<br />
'name' => '</span><span style="color:#f1c40f">required|max:255'</span><span style="color:#ffffff">,<br />
]);</span></p>
<p><span style="color:#ffffff"> // タスクの作成処理…<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p>これは「<strong>name</strong>」フィールドの入力値に<span style="color:#2980b9"><strong>何かしらの値が入力</strong></span>されていて、かつ<span style="color:#2980b9"><strong>255字以内</strong></span>であることをチェックしています。</p>
<p>バリデーションが失敗した場合のリダイレクト処理を記載していないことに気づくでしょう。</p>
<p>自動的に直前のページにリダイレクトする仕組みです。</p>
<p>かつ、sessionへフラッシュデータの保存も自動で行われます。</p>
<p> </p>
<h2>エラーの表示</h2>
<p>次は<strong>$errors</strong>変数は子ビューの「<strong>@include('common.errors')</strong>」の部分で表示させるようにしましょう。</p>
<p>「<strong>resources/views/common/errors.blade.php</strong>」を作成して以下の実装をしましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000"><span style="color:#ffffff"><!-- resources/views/common/errors.blade.php --></span>
<p><span style="color:#ffffff">@if (count($errors) > 0)<br />
<!-- Form Error List --><br />
<div class="alert alert-danger"><br />
<strong>入力値に誤りがあります。</strong></span></p>
<p><span style="color:#ffffff"> <br><br></span></p>
<p><span style="color:#ffffff"> <ul><br />
@foreach ($errors->all() as $error)<br />
<li>{{ $error }}</li><br />
@endforeach<br />
</ul><br />
</div><br />
@endif</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>データベースへの値の追加</h2>
<p>次は値をデータベースに追加する処理を記載します。「<strong>TaskController</strong>」に以下の<strong>store</strong>メソッドの続きを記載します。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* 新しいタスクの作成<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function <strong>store</strong>(Request $request)<br />
{<br />
$this->validate($request, [<br />
'name' => 'required|max:255',<br />
]);</span></p>
<p><span style="color:#f1c40f"> $request->user()->tasks()->create([<br />
'name' => $request->name,<br />
]);</span></p>
<p><span style="color:#f1c40f"> </span><span style="color:#ffffff"> return redirect('/tasks');</span><br />
<span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p>今回使用する<strong>create</strong>メソッドは属性の配列を受け取り、データベースへ保存する前に、関連するモデルの外部キー値を自動的に設定します。</p>
<p><strong>create</strong>メソッドは、<strong>$request->user()</strong>でアクセスできる現在の認証済みユーザのIDを指定したタスクのuser_idプロパティへ自動的に設定します。</p>
<p> </p>
<h2>データベースから値を取得</h2>
<p>保存した値を取得する処理を実装します。</p>
<p>「<strong>TaskController@index</strong>」の処理を以下の様に変更しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* ユーザーの全タスクをリスト表示<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function index(Request $request)<br />
{<br />
</span><span style="color:#f1c40f">$tasks = $request->user()->tasks()->get();</span></p>
<p><span style="color:#ffffff"> return view('tasks.index', [<br />
'tasks' => $tasks,<br />
]);<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p>これでも動作しますが、全データアクセスに対して利用する<strong>TaskRepository</strong>をLaravelの<strong>依存注入</strong>能力を使い、「<strong>TaskController</strong>」に注入することにしましょう。</p>
<p> </p>
<h2>依存注入</h2>
<p>「<strong>Task</strong>」モデルとの全アクセスロジックを持つ、「<strong>TaskRepository</strong>」を定義します。</p>
<p>「<strong>app/Repositories</strong>」ディレクトリを作成し、「<strong>TaskRepository</strong>」ファイルを作成しましょう。</p>
<p>以下の様に実装しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App\Repositories;</span></p>
<p><span style="color:#ffffff">use App\User;</span></p>
<p><span style="color:#ffffff">class </span><span style="color:#f1c40f">TaskRepository</span><br />
<span style="color:#ffffff">{<br />
/**<br />
* 指定ユーザーの全タスク取得<br />
*<br />
* @param User $user<br />
* @return Collection<br />
*/</span><br />
<span style="color:#f1c40f"> public function forUser(User $user)<br />
{<br />
return $user->tasks()<br />
->orderBy('created_at', 'asc')<br />
->get();<br />
}</span><br />
<span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>リポジトリー注入</h2>
<p>実際にリポジトリーを注入してみましょう。</p>
<p>「<span style="color:#000000"><strong>TaskController </strong></span>」を以下の内容に書き換えます。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App\Http\Controllers;</span></p>
<p><span style="color:#ffffff">use App\Task;<br />
use App\Http\Requests;<br />
use Illuminate\Http\Request;<br />
use App\Http\Controllers\Controller;<br />
use App\Repositories\TaskRepository;</span></p>
<p><span style="color:#ffffff">class TaskController extends Controller<br />
{<br />
<br />
/**<br />
* タスクリポジトリーインスタンス<br />
*<br />
* @var TaskRepository<br />
*/</span><br />
<span style="color:#f1c40f"> protected $tasks;</span></p>
<p><br />
<span style="color:#ffffff"> /**<br />
* 新しいコントローラーインスタンスの生成<br />
*<br />
* @param TaskRepository $tasks<br />
* @return void<br />
*/<br />
public function __construct(TaskRepository $tasks)<br />
{<br />
$this->middleware('auth');</span></p>
<p><span style="color:#ffffff"> </span><span style="color:#f1c40f">$this->tasks = $tasks;</span><br />
<span style="color:#ffffff"> }<br />
</span></p>
<p><span style="color:#ffffff"> /**<br />
* ユーザーの全タスクをリスト表示<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function index(Request $request)<br />
{<br />
return view('tasks.index', [<br />
</span><span style="color:#f1c40f">'tasks' => $this->tasks->forUser($request->user()),</span><br />
<span style="color:#ffffff"> ]);<br />
}<br />
<br />
/**<br />
* 新しいタスクの作成<br />
*<br />
* @param Request $request<br />
* @return Response<br />
*/<br />
public function store(Request $request)<br />
{<br />
$this->validate($request, [<br />
'name' => 'required|max:255',<br />
]);</span></p>
<p><span style="color:#ffffff"> $request->user()->tasks()->create([<br />
'name' => $request->name,<br />
]);</span></p>
<p><span style="color:#ffffff"> return redirect('/tasks');<br />
}<br />
<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>ビューに値を表示</h2>
<p>データベースから取得した値をビューに表示しましょう。</p>
<p>「<strong>resources/views/tasks/index.blade.php</strong>」を以下の内容に書き換えましょう。</p>
<p>(※黄色が追加した部分です)</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><!-- resources/views/tasks/index.blade.php --></span></p>
<p><span style="color:#ffffff">@extends('layouts.app')</span></p>
<p><span style="color:#ffffff">@section('content')</span></p>
<p><span style="color:#ffffff"> <!-- Bootstrapの定形コード… --></span></p>
<p><span style="color:#ffffff"> <div class="panel-body"><br />
<!-- バリデーションエラーの表示 --><br />
@include('common.errors')</span></p>
<p><span style="color:#ffffff"> <!-- 新タスクフォーム --><br />
<form action="{{ url('task') }}" method="POST" class="form-horizontal"><br />
{{ csrf_field() }}</span></p>
<p><span style="color:#ffffff"> <!-- タスク名 --><br />
<div class="form-group"><br />
<label for="task-name" class="col-sm-3 control-label">Task</label></span></p>
<p><span style="color:#ffffff"> <div class="col-sm-6"><br />
<input type="text" name="name" id="task-name" class="form-control"><br />
</div><br />
</div></span></p>
<p><span style="color:#ffffff"> <!-- タスク追加ボタン --><br />
<div class="form-group"><br />
<div class="col-sm-offset-3 col-sm-6"><br />
<button type="submit" class="btn btn-default"><br />
<i class="fa fa-plus"></i> Add Task<br />
</button><br />
</div><br />
</div><br />
</form><br />
</div></span></p>
<p><span style="color:#f1c40f"> <!-- 現在のタスク --><br />
@if (count($tasks) > 0)<br />
<div class="panel panel-default"><br />
<div class="panel-heading"><br />
Current Tasks<br />
</div></span></p>
<p><span style="color:#f1c40f"> <div class="panel-body"><br />
<table class="table table-striped task-table"></span></p>
<p><span style="color:#f1c40f"> <!-- テーブルヘッダ --><br />
<thead><br />
<th>Task</th><br />
<th> </th><br />
</thead></span></p>
<p><span style="color:#f1c40f"> <!-- テーブル本体 --><br />
<tbody><br />
@foreach ($tasks as $task)<br />
<tr><br />
<!-- Task Name --><br />
<td class="table-text"><br />
<div>{{ $task->name }}</div><br />
</td></span></p>
<p><span style="color:#f1c40f"> <td><br />
<strong> <!-- TODO: 削除ボタン --></strong><br />
</td><br />
</tr><br />
@endforeach<br />
</tbody><br />
</table><br />
</div><br />
</div><br />
@endif</span><br />
<span style="color:#ffffff">@endsection</span></p>
</td>
</tr>
</tbody>
</table>
<p>「<strong><span style="color:#000000">$tasks</span></strong>」が0件でない場合、foreach文で回して一件ずつ「<strong>name</strong>」を表示します。</p>
<p> </p>
<h2>データベースの値の削除</h2>
<p>先ほど追加したコードの「<strong><span style="color:#f1c40f"><!-- TODO: 削除ボタン --></span></strong>」の部分に、以下のコードを追加して削除ボタンを追加しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><form action="{{ </span><span style="color:#f1c40f">url('task/'.$task->id)</span><span style="color:#ffffff"> }}" method="</span><span style="color:#f1c40f">POST</span><span style="color:#ffffff">"><br />
{{ csrf_field() }}<br />
{{ method_field('</span><span style="color:#f1c40f">DELETE</span><span style="color:#ffffff">') }}</span></p>
<p><span style="color:#ffffff"> <button type="submit" id="delete-task-{{ $task->id }}" class="btn btn-danger"><br />
<i class="fa fa-btn fa-trash"></i>削除<br />
</button><br />
</form></span><br />
</p>
</td>
</tr>
</tbody>
</table>
<p>削除ボタンをクリックすると、<span style="color:#e74c3c"><strong>DELETE</strong></span>でリクエストします。</p>
<p>formタグ内では<span style="color:#e74c3c"><strong>POST</strong></span>を使用していますが、これはHTMLのフォームが許容しているのがGETとPOSTのみなので、とりあえず記載しているだけです。</p>
<p>実際はDELETEのリクエストとなります。</p>
<p>ボタンがクリックされると、DELETE 「<strong>/task</strong>」リクエストがアプリケーションに送信され、<strong>TaskController@destroy</strong>メソッドが起動されます。</p>
<p> </p>
<h2>認可</h2>
<p>実装予定のdestroyメソッドを見てみましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">Route::delete('</span><span style="color:#f1c40f">/task/{task}</span><span style="color:#ffffff">', 'TaskController@destroy');</span></p>
<p> </p>
<p><span style="color:#ffffff">public function destroy(Request $request, Task $task) { </span></p>
<p><span style="color:#ffffff">// </span></p>
<p><span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p>ルート中の{task}変数が、コントローラメソッド中の$task変数定義と一致するため、</p>
<p>Laravelの暗黙的モデル結合により、対応するタスクモデルのインスタンスが自動的に依存注入されます。</p>
<p> </p>
<p>このままだと「<strong>/tasks/{task}</strong>」のURLへランダムなタスクIDを渡すことで、悪意のあるリクエストを仕込むことが可能です。</p>
<p>Taskインスタンスが実際に認証済みユーザが所有していることを確認するため、Laravelの認可機能を使う必要があります。</p>
<p> </p>
<h2>ポリシー</h2>
<p>認証ロジックを単純で小さなクラスへ系統立てるため、Laravelは「ポリシー」を使っています。</p>
<p>通常、各ポリシーはモデルに対応しています。</p>
<p>では、コマンドを使用して「<strong>TaskPolicy」</strong>を作成しましょう。「<strong>app/Policies/TaskPolicy.php</strong>」として生成されます。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">php artisan </span><span style="color:#f1c40f">make:policy</span><span style="color:#ffffff"> TaskPolicy</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>次にdestroyメソッドをポリシーへ追加します。</p>
<p>このメソッドは<strong>User</strong>インスタンスと<strong>Task</strong>インスタンスを引数に取ります。</p>
<p>このメソッドはシンプルにユーザのIDがタスクのuser_idと一致するかを調べるだけです。</p>
<p>実際、全ポリシーメソッドはtrueかfalseを返す必要があります。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff"><?php</span></p>
<p><span style="color:#ffffff">namespace App\Policies;</span></p>
<p><span style="color:#ffffff">use App\User;<br />
use App\Task;<br />
use Illuminate\Auth\Access\HandlesAuthorization;</span></p>
<p><span style="color:#ffffff">class TaskPolicy<br />
{<br />
</span><span style="color:#f1c40f">use HandlesAuthorization;</span></p>
<p><span style="color:#ffffff"> /**<br />
* 指定されたユーザーが指定されたタスクを削除できるか決定<br />
*<br />
* @param User $user<br />
* @param Task $task<br />
* @return bool<br />
*/</span><br />
<span style="color:#f1c40f"> public function destroy(User $user, Task $task)<br />
{<br />
return $user->id === $task->user_id;<br />
}</span><br />
<span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p>最後にTaskモデルをTaskPolicyと関連付ける必要があります。</p>
<p>「<strong>app/Providers/AuthServiceProvider.php</strong>」ファイルの<strong>$policies</strong>プロパティに一行加えることで可能です。</p>
<p>これによりTaskインスタンスに対するアクションを認可したい場合に毎回使われるべきポリシーをLaravelに指定しています。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* アプリケーションにマップするポリシー<br />
*<br />
* @var array<br />
*/<br />
protected </span><span style="color:#f1c40f">$policies</span><span style="color:#ffffff"> = [<br />
'App\Task' => 'App\Policies\TaskPolicy',<br />
];</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<h2>アクションの認可</h2>
<p>これでポリシーが書き上がりましたので、destroyメソッドで使用しましょう。</p>
<p>Laravelの全コントローラーから、AuthorizesRequestトレイトにより提供されているauthorizeメソッドを呼び出せます。</p>
<p>「<strong>TaskController</strong>」に以下の内容を追記しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* 指定タスクの削除</span></p>
<p><span style="color:#ffffff"> *<br />
* @param Request $request<br />
* @param Task $task<br />
* @return Response<br />
*/<br />
public function destroy(Request $request, Task $task)<br />
{<br />
</span><span style="color:#f1c40f">$this->authorize('destroy', $task);</span></p>
<p><span style="color:#ffffff"> // タスクの削除処理...<br />
}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p> </p>
<h2>データベースの値削除</h2>
<p>「<strong>TaskController</strong>」の<strong>destroy</strong>メソッドに以下の内容を追記しましょう。</p>
<table border="1" cellpadding="1" cellspacing="1" style="width:500px">
<tbody>
<tr>
<td style="background-color:#000000">
<p><span style="color:#ffffff">/**<br />
* 指定タスクの削除<br />
*<br />
* @param Request $request<br />
* @param Task $task<br />
* @return Response<br />
*/<br />
public function destroy(Request $request, Task $task)<br />
{<br />
$this->authorize('destroy', $task);</span></p>
<p><span style="color:#f1c40f"> $task->delete();</span></p>
<p><span style="color:#ffffff"> return redirect('/tasks');</span><br />
<span style="color:#ffffff">}</span></p>
</td>
</tr>
</tbody>
</table>
<p> </p>
<p>これで今回のWebアプリ作成は完了となります。</p>
<p>お疲れさまでした。</p>
<p> </p>
<p> </p>