Laravel まとめ6(コメント表示/保存)

#コメント表示/保存まで
(#26,27)
http://dotinstall.com/lessons/basic_laravel/36127


#コメント用のデータベースを作る

モデルとmigrationを合わせて作る

```
php artisan make:model Comment --migration
```

#マイグレーションファイルを修正

```　/myblog/database/migration_create_comments_table.php

<?php

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

class CreateCommentsTable extends Migration
{
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->string('body');
            $table->timestamps();

            $table->foreign('post_id')
                  ->references('id')
                  ->on('posts')
                  ->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::drop('comments');
    }
}
```

- 必要となるカラム→一行コメントなので string('body')

- コメントを postに紐付ける
→integer('post_id')
→負の値になることは無いので、unsigned()

- foreign('post_id')
references('id')
どこの→idposts

- onDelete()
cascade→postが削除された時に関連するコメントも一気に削除



```/myblog/app/Comment.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    // 追加

    protected $fillable = ['body'];

    public function post() {
      return $this->belongsTo('App\Post');
    }
}
```

```/myblog/app/Post.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
    protected $fillable = ['title', 'body'];

// 追加
    public function comments() {
      return $this->hasMany('App\Comment');
    }
}
```

#Migrationする

```
php artisan migrate
```

```
php artisan make:migration drop_summary_from_posts_table --table=posts
php artisan migrate
```
※既存のtableを修正するには --tableオプションをつける


```drop_summary_from_posts_table.php

<?php

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

class DropSummaryFromPostsTable extends Migration
{
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
          $table->dropColumn('summary');
        });
    }

     public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
          $table->string('summary');
        });
    }
}
```

#CommentsControllerを作る

```
php artisan make:controller CommentsController
```

#CommentsControllerを追記

```/myblog/app/Http/Controllers/CommentsController.php 

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Comment;
use App\Post;

class CommentsController extends Controller
{
    //
    public function store(Request $request, $postId) {
      $this->validate($request, [
        'body' => 'required'
      ]);

      $comment = new Comment(['body' => $request->body]);
      $post = Post::findOrFail($postId);
      $post->comments()->save($comment);

      return redirect()
             ->action('PostsController@show', $post->id);
    }
}
```


#ルーツ

```　/myblog/app/Http/routes.php

<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/', 'PostsController@index');
Route::get('/posts/create', 'PostsController@create');
Route::get('/posts/{id}', 'PostsController@show');
Route::get('/posts/{id}/edit', 'PostsController@edit');
Route::post('/posts', 'PostsController@store');
Route::patch('/posts/{id}', 'PostsController@update');
Route::delete('/posts/{id}', 'PostsController@destroy');
Route::post('/posts/{post}/comments', 'CommentsController@store');
```

- commentsに対して、postが飛んできたら、CommentsControllerのstoreメソッドを呼ぶ。



#Controller

```/myblog/app/Http/Controllers/CommentsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Comment;
use App\Post;

class CommentsController extends Controller
{
    //
    public function store(Request $request, $postId) {
      $this->validate($request, [
        'body' => 'required'
      ]);

      $comment = new Comment(['body' => $request->body]);
      $post = Post::findOrFail($postId);
      $post->comments()->save($comment);

      return redirect()
             ->action('PostsController@show', $post->id);
    }
}
```

```
[storeメソッドを作る]
・ バリデーションつける
・ コメントをセーブする
・ リダイレクト処理
```

#View

```/myblog/resources/views/posts/show.blade.php

@extends('layouts.default')
@section('title', 'Blog Detail')
@section('content')
<h1>
  <a href="{{ url('/') }}" class="pull-right fs12">Back</a>
  {{ $post->title }}
</h1>
<p>{!! nl2br(e($post->body)) !!}</p>

//コメント表示

<h2>Comments</h2>
<ul>
  @forelse ($post->comments as $comment)
  <li>{{ $comment->body }}</li>
  @empty
  <li>No comment yet</li>
  @endforelse
</ul>

//コメント追加フォーム

<h2>Add New Comment</h2>
<form method="post" action="{{ action('CommentsController@store', $post->id) }}">
  {{ csrf_field() }}
  <p>
    <input type="text" name="body" placeholder="body" value="{{ old('body') }}">
    @if ($errors->has('body'))
    <span class="error">{{ $errors->first('body') }}</span>
    @endif
  </p>
  <p>
    <input type="submit" value="Add Comment">
  </p>
</form>
@endsection
```

- comment表示部分を追記