Laravel まとめ7(サンプル仕上げ)

http://dotinstall.com/lessons/basic_laravel/36127
(#28,29)

- コメント削除機能
- 仕上げ

##ルーツ

- 特定のルートに一致したらその後のルート定義は無視される

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

<?php

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


Route::group(['middleware' => ['web']], function () {

    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');
    Route::delete('/posts/{post}/comments/{comment}', 'CommentsController@destroy');
});
```


##バリデーション

```/myblog/app/Http/Requests/PostRequest.php

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class PostRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // return false;
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'title' => 'required|min:3',
          'body' => 'required'
        ];
    }
}
```

```/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');
    }
}
```

```/myblog/app/Comment.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    //
    protected $fillable = ['body'];

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

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

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

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

class PostsController extends Controller
{
    public function index() {
      $posts = Post::latest('created_at')->get();
      return view('posts.index')->with('posts', $posts);
    }

    public function show($id) {
      $post = Post::findOrFail($id);
      return view('posts.show')->with('post', $post);
    }

    public function edit($id) {
      $post = Post::findOrFail($id);
      return view('posts.edit')->with('post', $post);
    }

    public function destroy($id) {
      $post = Post::findOrFail($id);
      $post->delete();
      return redirect('/')->with('flash_message', 'Post Deleted!');
    }

    public function create() {
      return view('posts.create');
    }

    public function store(PostRequest $request) {
      $post = new Post();
      $post->title = $request->title;
      $post->body = $request->body;
      $post->save();
      return redirect('/')->with('flash_message', 'Post Added!');
    }

    public function update(PostRequest $request, $id) {
      $post = Post::findOrFail($id);
      $post->title = $request->title;
      $post->body = $request->body;
      $post->save();
      return redirect('/')->with('flash_message', 'Post Updated!');
    }

}
```

```/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);
    }

//$post を $postId で取得。紐付いた $commentId のコメントを削除

    public function destroy($postId, $commentId) {
      $post = Post::findOrFail($postId);
      $post->comments()->findOrFail($commentId)->delete();

//リダイレクト
      return redirect()
             ->action('PostsController@show', $post->id);
    }
}
```


#View

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

@extends('layouts.default')

@section('title', 'Blog Posts')

@section('content')
<h1>
  <a href="{{ url('/posts/create') }}" class="pull-right fs12">Add New</a>
  Posts
</h1>
<ul>
  @forelse ($posts as $post)
  <li>
    <a href="{{ action('PostsController@show', $post->id) }}">{{ $post->title }}</a>
    <a href="{{ action('PostsController@edit', $post->id) }}" class="fs12">[Edit]</a>
    <form action="{{ action('PostsController@destroy', $post->id) }}" id="form_{{ $post->id }}" method="post" style="display:inline">
    {{ csrf_field() }}
    {{ method_field('delete') }}
      <a href="#" data-id="{{ $post->id }}" onclick="deletePost(this);" class="fs12">[x]</a>
    </form>
  </li>
  @empty
  <li>No posts yet</li>
  @endforelse
</ul>

<script>
function deletePost(e) {
  'use strict';

  if (confirm('are you sure?')) {
    document.getElementById('form_' + e.dataset.id).submit();
  }
}
</script>
@endsection

```

```/myblog/resources/views/layouts/default.blade.php

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>@yield('title')</title>
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  @if (session('flash_message'))
  <div class="flash_message" onclick="this.classList.add('hidden')">{{ session('flash_message') }}</div>
  @endif
  <div class="container">
    @yield('content')
  </div>
</body>
</html>
```

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

@extends('layouts.default')
@section('title', 'Edit Post')
@section('content')
<h1>
  <a href="{{ url('/') }}" class="pull-right fs12">Back</a>
  Edit Post
</h1>
<form method="post" action="{{ url('/posts', $post->id) }}">
  {{ csrf_field() }}
  {{ method_field('patch') }}
  <p>
    <input type="text" name="title" placeholder="title" value="{{ old('title', $post->title) }}">
    @if ($errors->has('title'))
    <span class="error">{{ $errors->first('title') }}</span>
    @endif
  </p>
  <p>
    <textarea name="body" placeholder="body">{{ old('body', $post->body) }}</textarea>
    @if ($errors->has('body'))
    <span class="error">{{ $errors->first('body') }}</span>
    @endif
  </p>
  <p>
    <input type="submit" value="Update">
  </p>
</form>
@endsection
```

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

@extends('layouts.default')
@section('title', 'Add New')
@section('content')
<h1>
  <a href="{{ url('/') }}" class="pull-right fs12">Back</a>
  Add New
</h1>
<form method="post" action="{{ url('/posts') }}">
  {{ csrf_field() }}
  <p>
    <input type="text" name="title" placeholder="title" value="{{ old('title') }}">
    @if ($errors->has('title'))
    <span class="error">{{ $errors->first('title') }}</span>
    @endif
  </p>
  <p>
    <textarea name="body" placeholder="body">{{ old('body') }}</textarea>
    @if ($errors->has('body'))
    <span class="error">{{ $errors->first('body') }}</span>
    @endif
  </p>
  <p>
    <input type="submit" value="Add New">
  </p>
</form>
@endsection
```

```/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 }}
    <form action="{{ action('CommentsController@destroy', [$post->id, $comment->id]) }}" id="form_{{ $comment->id }}" method="post" style="display:inline">
    {{ csrf_field() }}
    {{ method_field('delete') }}
      <a href="#" data-id="{{ $comment->id }}" onclick="deleteComment(this);" class="fs12">[x]</a>
    </form>
  </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>

<script>
function deleteComment(e) {
  'use strict';

  if (confirm('are you sure?')) {
    document.getElementById('form_' + e.dataset.id).submit();
  }
}
</script>
@endsection
```

#DB

```/myblog/database/migrations/add_summary_to_posts_table.php

<?php

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

class AddSummaryToPostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
          $table->string('summary');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function (Blueprint $table) {
          $table->dropColumn('summary');
        });
    }
}
```

#表示

![1.png](https://qiita-image-store.s3.amazonaws.com/0/62264/08e7fecc-d8af-46ec-d35c-045f654d21d9.png)

![2.png](https://qiita-image-store.s3.amazonaws.com/0/62264/cf64b0fd-5831-f803-05e4-4fc1ba7f0bce.png)

![スクリーンショット 2016-07-21 19.36.53.png](https://qiita-image-store.s3.amazonaws.com/0/62264/92cc1db1-d835-7acb-284b-be198781727d.png)

![スクリーンショット 2016-07-21 19.37.03.png](https://qiita-image-store.s3.amazonaws.com/0/62264/29fc5191-b38e-2c69-02ed-86030bbd7acf.png)