Laravel5.2のチュートリアルを試す


↓こちらのチュートリアルを試します。
[Laravel 5.2 中級者向けタスクリスト](https://readouble.com/laravel/5.2/ja/quickstart-intermediate.html)
ただし、ここで使用しているLaravelのバージョンは5.3です。

- プロジェクトの作成

```bash:
php composer.phar create-project --prefer-dist laravel/laravel mytodo
```

- データベースの作成

```sql:
create database laravel_mytodo;
grant all on laravel_mytodo.* to dbuser@localhost identified by 'Abc1234';
```

- プロジェクトの初期設定

```bash:.env
DB_DATABASE=laravel_mytodo
DB_USERNAME=dbuser
DB_PASSWORD=Abc1234
```

```php:config/app.php
'name' => 'My ToDo',
'timezone' => 'Asia/Tokyo',
'locale' => 'ja',
```

- テーブルの作成

```bash:
php artisan make:migration create_tasks_table --create=tasks
```

```php:database/migrations/20XX_XX_XX_XXXXXX_create_tasks_table.php
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('name');
            $table->timestamps();
        });
    }
```

```bash:
php artisan migrate
```

- モデルの作成

```bash:
php artisan make:model Task
```

```php:app/Task.php
class Task extends Model
{
    protected $fillable = ['name'];
}
```

- リレーションの設定

```php:app/User.php
    public function tasks() {
    	return $this->hasMany(Task::class);
    }
```

```php:app/Task.php
    public function user() {
    	return $this->belongsTo(User::class);
    }
```

- 認証

```bash:
php artisan make:auth
```

- タスク表示へのリンクを作成

チュートリアルではログインしたらタスク表示にリダイレクトしていますが、
ここではHomeを表示して、タスク表示へのリンクを作成することにします。

```php:resources/views/home.blade.php
<a href="{{ url('/tasks') }}">ToDo List</a>
```

- コントローラーの作成

```bash:
php artisan make:controller TaskController
```

```php:routes/web.php
Route::get('/tasks', 'TaskController@index');
Route::post('/task', 'TaskController@store');
Route::delete('/task/{task}', 'TaskController@destroy');
```

```php:app/Http/Controllers/TaskController.php
    public function __construct() {
    	$this->middleware('auth');
    }
```

- index表示

```php:resources/views/tasks/index.blade.php
@extends('layouts.app')

@section('content')
@include('common.errors')
<form action="{{ url('task') }}" method="POST">
	{{ csrf_field() }}
	<label for="task-name">Task</label>
	<input type="text" name="name" id="task-name">
	<button type="submit">Add Task</button>
</form>
@endsection
```

```php:app/Http/Controllers/TaskController.php
    public function index(Request $request) {
    	return view('tasks.index');
    }
```

- タスク追加

```php:app/Http/Controllers/TaskController.php
    public function store(Request $request) {
    	$this->validate($request, [
    		'name' => 'required|max:255',
    	]);

    	$request->user()->tasks()->create([
    		'name' => $request->name,
    	]);
    	
    	return redirect('/tasks');
    }
```

```php:resources/views/tasks/index.blade.php
@include('common.errors')
```

```php:resources/views/common/errors.blade.php
@if (count($errors) > 0)
	<strong>おや？何かがおかしいようです！</strong>
	<ul>
		@foreach ($errors->all() as $error)
			<li>{{ $error }}</li>
		@endforeach
	</ul>
@endif
```

- タスク表示

```php:app/Http/Controllers/TaskController.php
    public function index(Request $request) {
    	$tasks = $request->user()->tasks()->get();
    	return view('tasks.index', [
    		'tasks' => $tasks,
    	]);
    }
```

```php:resources/views/tasks/index.blade.php
@if (count($tasks) > 0)
	Current Tasks
	<table>
		<thead>
			<th>Task</th>
			<th>&nbsp;</th>
		</thead>
		<tbody>
			@foreach ($tasks as $task)
				<tr>
					<td>{{ $task->name }}</td>
					<td></td>
				</tr>
			@endforeach
		</tbody>
	</table>
@endif
```

- リポジトリの作成

```php:app/Repositories/TaskRepository.php
<?php

namespace App\Repositories;

use App\User;

class TaskRepository {
	public function forUser(User $user) {
		return $user->tasks()->orderBy('created_at', 'asc')->get();
	}
}
```

```php:app/Http/Controllers/TaskController.php
use App\Repositories\TaskRepository;

class TaskController extends Controller
{
	protected $tasks;

    public function __construct(TaskRepository $tasks) {
    	$this->middleware('auth');
    	$this->tasks = $tasks;
    }

    public function index(Request $request) {
		return view('tasks.index', [
			'tasks' => $this->tasks->forUser($request->user()),
		]);
    }
}
```

- タスクの削除

```php:resources/views/tasks/index.blade.php
    <form action="{{ url('task/'.$task->id) }}" method="POST">
        {{ csrf_field() }}
        {{ method_field('DELETE') }}
        <button type="submit">削除</button>
    </form>
```

```bash:
php artisan make:policy TaskPolicy
```

```php:app/Policies/TaskPolicy.php
use App\Task;

    public function destroy(User $user, Task $task) {
    	return $user->id === $task->user_id;
    }
```

```php:app/Providers/AuthServiceProvider.php
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    	'App\Task' => 'App\Policies\TaskPolicy',
    ];
```

```php:app/Http/Controllers/TaskController.php
use App\Task;

    public function destroy(Request $request, Task $task) {
    	$this->authorize('destroy', $task);
    	$task->delete();
    	return redirect('/tasks');
    }
```

- 確認

```bash:
php artisan serve --host 192.168.33.10 --port 8000
```