Laravel5.4: Form作成(illuminate/htmlではなくて、laravelcollective/htmlで)

Why?

  • フォームヘルパーを使うと、Form作るのが楽になる
  • laravelcollective/htmlパッケージをプロジェクトに導入しなくてはならない
    • NG: illuminate/html メンテ止まってる
    • OK: laravelcollective/html メンテされてる
  • Laravel Collective は、Laravel本体から外されたパッケージをメンテするプロジェクト

How to?

laravelcollective/htmlをプロジェクトに追加

  • インストールコマンドでvendorに追加(何気に時間がかかる)
$ composer require laravelcollective/html
  • その結果、composer.json に laravelcollective/html が追加され、インストールもされた
$ cat composer.json
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "laravelcollective/html": "^5.4"
    },
...
  • ProviderとAliaseを登録
    'providers' => [
...
        Collective\Html\HtmlServiceProvider::class,
...

    'aliases' => [
...
        'Form' => Collective\Html\FormFacade::class,
        'Html' => Collective\Html\HtmlFacade::class
...

登録フォームの実装

  • Routingを追加(順番注意): routes/web.php
Route::get('articles', 'ArticlesController@index');
Route::get('articles/create', 'ArticlesController@create');
Route::get('articles/{id}', 'ArticlesController@show');
  • Controllerを追加(順番注意): app/Http/Controllers/ArticlesController.php
public function create() {
    return view('articles.create');
}
  • Viewを書く: resources/views/articles/create.blade.php
@extends('app')

@section('content')
  <h1>Write a New Article</h1>
  <hr />

  {!! Form::open(['url' => 'articles']) !!}
    <div class="form-group">
      {!! Form::label('title', 'Title') !!}
      {!! Form::text('title', null, ['class' => 'form-control']) !!}
    </div>
    <div class='form-group'>
      {!! Form::label('body', 'Body') !!}
      {!! Form::text('body', null, ['class' => 'form-control']) !!}
    </div>
    <div class='form-group'>
      {!! Form::submit('Add Article', ['class' => 'btn btn-primary form-control']) !!}
    </div>
  {!! Form::close() !!}
@stop

登録APIの実装

  • Routingを追加(順番注意): app/Http/routes.php
Route::post('articles', 'ArticlesController@store');
  • Controllerを追加
namespace App\Http\Controllers;

use Request;
use App\Article;
use Carbon\Carbon;

class ArticlesController extends Controller
{
    ...
    public function store() {
        $input = Request::all();
        $input['publishd_at'] = Carbon::now();
        Article::create($input);
        return redirect('articles');
    }

逆順ソートで表示

  • リスト表示時にlatestを使う
class ArticlesController extends Controller {
 
    public function index() {
        $articles = Article::latest('published_at')->get();
        return view('articles.index', compact('articles'));
    }
  • vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
    public function latest($column = 'created_at')
    {
        return $this->orderBy($column, 'desc');
    }

ハマりどころ

参照