読者です 読者をやめる 読者になる 読者になる

Laravel 5.4: Model, Controller, Viewワークフロー

Laravel

Why?

  • Articleの一覧、詳細を作ることで、一通りのModel, Controller, Viewワークフローを流す

How to

Articleの一覧を作る

  • app/Http/routes.phpにRoutingを追加
Route::get('articles', 'ArticlesController@index');
  • Controllerを追加 (laravel 5.2から–plainオプションはデフォルトになったので不要)
    • app/Http/Controllers/ArticlesController.phpが追加される
$ php artisan make:controller ArticlesController
  • app/Http/Controllers/ArticlesController.phpにindexメソッドを追加 (まずはviewに渡さずにプレーンに表示)
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Article;

class ArticlesController extends Controller
{
    public function index() {
        $articles = Article::all();
        return $articles;
    }
}
  • プレーンなレスポンスが帰ってくる
[
    {
        id: 1
        title: "My Update First Article"
        body: "Lorem ipsum"
        ...
    }
]
  • app/Http/Controllers/ArticlesController.phpViewからViewに渡す
    public function index() {
        $articles = Article::all();
        return view('articles.index', compact('articles'));
    }
  • View resources/views/articles/index.blade.php を追加
@extends('app')

@section('content')
  <h1>Articles</h1>
  <hr />
  @foreach ($articles as $article)
    <article>
      <h2>{{ $article->title }}</h2>
      <div class="body">{{ $article->body }}</div>
    </article>
  @endforeach
@stop

Articleの詳細を作る

  • app/Http/routes.phpにRoutingを追加
Route::get('articles/{id}', 'ArticlesController@show');
  • app/Http/Controllers/ArticlesController.phpにshowメソッドを追加
    public function show($id) {
        $article = Article::findOrFail($id);
        return view('articles.show', compact('article'));
    }
  • View resources/views/articles/show.blade.php を追加
@extends('app')

@section('content')
  <h1>{{ $article->title }}</h1>
  <article>
    <div class="body">{{ $article->body }}</div>
  </article>
@stop

一覧と詳細ページを繋げる

  • resources/views/articles/show.blade.phpにリンク追加
@extends('app')

@section('content')
  <h1>{{ $article->title }}</h1>
  <article>
    <div class="body">{{ $article->body }}</div>
  </article>
  <a href="/articles/">&lt; Back to list</a>
@stop
  • resources/views/articles/index.blade.phpにリンク追加
@extends('app')

@section('content')
  <h1>Articles</h1>
  <hr />
  @foreach ($articles as $article)
    <article>
      <h2><a href="/articles/{{ $article->id }}">{{ $article->title }}</h2></a>
      <div class="body">{{ $article->body }}</div>
    </article>
  @endforeach
@stop

参考