Controller及びViewの作成

■ Controller の生成

$ php artisan make:controller XxxsController --resource

*ルーターを生成した際のコード
(Route::resource(‘xxx’, ‘XxxsController’); に合わせる。
*基本は複数形(必須ではない)
*Controllerファイルは、app/Http/controllers/ に生成。

■ routes/web.php で下記を定義

Route::resource('xxxs', 'XxxsController')

■ ご参考:ルーティング確認方法(Controller生成時)

php artisan route:list

■ Viewの作成

resources/views/ 直下に xxxフォルダを作成し以下ファイルを作成

resources/views/xxx/index.blade.php
resources/views/xxx/create.blade.php
resources/views/xxx/show.blade.php
resources/views/xxx/edit.blade.php

■ 各ファイルに以下を定義

@extends('layouts.app')
@section('content')
//
@endsection

*上記の@extends(‘layouts.app’)で以下のBladeを呼び出す

■ Bladeの活用

resources/views/ 直下に layoutsフォルダ作成し、app.blade.php を作成
共通部となる以下を作成。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>xxx</title>
    </head>

    <body>
        @yield('content')
    </body>
</html>

*@yield(‘content’) は、 @section(‘content’) … @endsection の中身により埋め込む。

■ Laravel Collective実装(form作成用等の事前準備)

composer.json の “require”に以下を追記

"laravelcollective/html": "5.5.*"

その後以下コマンド

$ composer update

■ 各レスポンスの実装

Index:
———

目的はレコードの一覧表示 = App\Xxx::all()
Controller から任意のView 呼び出しはview()を使う。

Controller:

app/Http/Controllers/XxxsController.phpファイルに以下を定義。

use App\xxx(モデル名);

*いちいちApp\を打たなくてよいため

View:

public function index(){
$xxxs = Xxx::all();
return view('xxxs.index', ['xxxs' => $xxxs,]);
}

resources/views/xxxs/index.blade.phpファイルに以下を定義。

@extends('layouts.app')
@section('content')
  <h1>(タイトル)</h1>
 @if (count($xxxs) > 0)
  <ul>
       @foreach ($xxxs as $xxx)
      <li>{{ $xxx->content }}</li>
      @endforeach
   </ul>
 @endif
@endsection

ご参考:動作の確認
1. Laravelサーバを起動

$ php artisan serve --host=$IP --port=$PORT

2. index のルーティングにアクセス
* “/” に続けて、web.phpの第一引数をバーに入力
*MySQLに接続していることが前提

 

Show:
———

Controller:

app/Http/Controllers/XxxsController.php

public function show($id)
{
$xxx = Xss::find($id);

return view('xxx.show', [
'xxx' => $xxx,
]);
}

View:

resources/views/xxxs/show.blade.php

@extends('layouts.app')

@section('content')

   <h1>id = {{ $xxx->id }} (のタイトル)</h1>

   <p>{{ $xxx->content }}</p>
@endsection

*動作確認は/1等の数字を入れる

尚、Indexのviewにshowをリンクする

View:

resources/views/xxxs/index.blade.phpファイルを以下に再定義。

@extends('layouts.app')

@section('content')

メッセージ一覧

@if (count($xxxs) > 0)

@foreach ($xxxs as $xxx)
@foreach ($xxxs as $xxx)

{!! link_to_route('xxxs.show', $xxx->id, ['id' => $xxx->id]) !!} : {{ $xxx->content }}

@endforeach
@endif
@endsection

ご参考: link_to_routeの引数
[ルーティング名, リンクにしたい文字列, URL内のパラメータに代入したい値, HTMLタグの属性を配列形式で指定]

Create:
———

Controller:

app/Http/Controllers/xxxsController.php

public function create()
{
$xxx = new xxx;

return view('xxxs.create', [
'xxx' => $xxx,
]);
}

View:

resources/views/xxxs/index.blade.php

{!! link_to_route('xxxs.create', '新規メッセージの投稿') !!}

@endsection

resources/views/xxxs/create.blade.php

 

ご参考:
VIEWでPHPの変数や関数の結果を表示する場合、
{{, }} – tmlspecialchars適用。
基本PHPではこちらを使う。

{!!, !!} – そのまま表示
Laravel Collectiveやファサードが生成するHTML出力時

@extends('layouts.app')

@section('content')

<h1>新規作成ページ</h1>
{!! Form::model($xxx, ['route' => 'xxxs.store']) !!}

{!! Form::label('content', 'メッセージ:') !!}
{!! Form::text('content') !!}

{!! Form::submit('投稿') !!}

{!! Form::close() !!}

Store:
———

Create のページから送信されるフォームを処理

Controller:

app/Http/Controllers/xxxsController.php

public function store(Request $request)
{
$xxx = new xxx;
$xxx->content = $request->content;
$xxx->save();

return redirect('/');
}

受信したフォーム内容は $request に入っており、
$requestからcontentを取り出し、新規メッセージに代入し、保存。

Edit:
———

Controller:

app/Http/Controllers/XxxsController.php

public function edit($id)
{
$xxx = Xss::find($id);

return view('xxxs.edit', [
'xxx' => $xxx,
]);
}

resources/views/xxxs/edit.blade.php

@extends('layouts.app')

@section('content')

id: {{ $xxx->id }} のメッセージ編集ページ
{!! Form::model($xxx, ['route' => ['xxx.update', $xxx->id], 'method' => 'put']) !!}

{!! Form::label('content', 'メッセージ:') !!}
{!! Form::text('content') !!}

{!! Form::submit('更新') !!}

{!! Form::close() !!}

@endsection

resources/views/xxxs/show.blade.php
URL の直入力以外でも edit ビューにアクセスできるように詳細ページに以下リンクを追記

{!! link_to_route('xxxs.edit', 'このメッセージを編集', ['id' => $xxx->id]) !!}

Update:
———

edit が create と似ているように、 update は store に似ている

Controller:

app/Http/Controllers/XxxsController.php

public function update(Request $request, $id)
{
$xxx = Xxx::find($id);
$xxx->content = $request->content;
$xxx->save();

return redirect('/');
}

Destroy:
———

Controller:

app/Http/Controllers/XxxsController.php

public function destroy($id)
{
$xxx = Xxx::find($id);
$xxx->delete();

return redirect('/');
}

View:

show.blade.php に削除ボタン(フォーム)を設置

resources/views/xxxs/show.blade.php

{!! Form::model($xxx, ['route' => ['xxxs.destroy', $xxx->id], 'method' => 'delete']) !!}
{!! Form::submit('削除') !!}
{!! Form::close() !!}

 

ユーザーのエラー入力対応:

resources/views/ 直下に commons/ フォルダ作成
その中に error_xxxs.blade.php ファイルを作成

resources/views/commons/error_xxxs.blade.php

@if (count($errors) > 0)
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif

次に、app.blade.php 側に @include() を使ってつなげる。

resources/views/layouts/app.blade.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>xxx</title>
    </head>

    <body>
        @include('commons.error_xxxs')

        @yield('content')
    </body>
</html>

 カラムを増やすマイグレーション:

カラム追加用のマイグレーションファイルを生成します。 –table=xxxs でテーブルを指定。

$ php artisan make:migration add_title_to_xxxs_table --table=xxxs

ブランクで生成されたマイグレーションに、カラムの追加と削除を入れる

database/migrations/年月日時_add_title_to_xxxs_table.php の up と down 抜粋

$ public function up()
   {
       Schema::table('xxxs', function (Blueprint $table) {
           $table->string('title');
       });
   }

   public function down()
   {
       Schema::table('xxxs', function (Blueprint $table) {
           $table->dropColumn('title');
       });
   }

カラムが増えたことによって発生する作業:

Controllerとviewのみ

Controller(Store & update):

app/Http/Controllers/xxxsController.php の store アクション

public function store(Request $request)
   {
       $this->validate($request, [
           'title' => 'required|max:191',   // 追加
           'content' => 'required|max:191',
       ]);

       $xxx = new xxx;
       $xxx->title = $request->title;    // 追加
       $xxx->content = $request->content;
       $xxx->save();

       return redirect('/');
   }

app/Http/Controllers/xxxsController.php の update アクション

public function update(Request $request, $id)
   {
       $this->validate($request, [
           'title' => 'required|max:191',   // 追加
           'content' => 'required|max:191',
       ]);

       $xxx = xxx::find($id);
       $xxx->title = $request->title;    // 追加
       $xxx->content = $request->content;
       $xxx->save();

       return redirect('/');
   }

 

View:(全て)

フォームのあるファイル(create & edit):

resources/views/xxxs/create.blade.php

@extends('layouts.app')

@section('content')

    <h1>メッセージ新規作成ページ</h1>


    {!! Form::model($xxx, ['route' => 'xxxs.store']) !!}

        {!! Form::label('title', 'タイトル:') !!}
        {!! Form::text('title') !!}

        {!! Form::label('content', 'メッセージ:') !!}
        {!! Form::text('content') !!}

        {!! Form::submit('投稿') !!}

    {!! Form::close() !!}

@endsection

resources/views/xxxs/edit.blade.php

@extends('layouts.app')

@section('content')

    <h1>id: {{ $xxx->id }} のメッセージ編集ページ</h1>

    {!! Form::model($xxx, ['route' => ['xxxs.update', $xxx->id], 'method' => 'put']) !!}

        {!! Form::label('title', 'タイトル:') !!}
        {!! Form::text('title') !!}

        {!! Form::label('content', 'メッセージ:') !!}
        {!! Form::text('content') !!}

        {!! Form::submit('更新') !!}

    {!! Form::close() !!}

@endsection

他:

resources/views/xxxs/index.blade.php

@extends('layouts.app')

@section('content')

    <h1>メッセージ一覧</h1>

    @if (count($xxxs) > 0)
        <ul>
            @foreach ($xxxs as $xxx)
                <li>{!! link_to_route('xxxs.show', $xxx->id, ['id' => $xxx->id]) !!} : {{ $xxx->title }} > {{ $xxx->content }}</li>
            @endforeach
        </ul>
    @endif

    {!! link_to_route('xxxs.create', '新規メッセージの投稿') !!}

@endsection

resources/views/xxxs/show.blade.php

@extends('layouts.app')

@section('content')

    <h1>id = {{ $xxx->id }} のメッセージ詳細ページ</h1>

    <p>タイトル: {{ $xxx->title }}</p>
    <p>メッセージ: {{ $xxx->content }}</p>

    {!! link_to_route('xxxs.edit', 'このメッセージ編集', ['id' => $xxx->id]) !!}

    {!! Form::model($xxx, ['route' => ['xxxs.destroy', $xxx->id], 'method' => 'delete']) !!}
        {!! Form::submit('削除') !!}
    {!! Form::close() !!}

@endsection

 

About TIER

TIERは、Global、DX、HRの3軸により 大手企業から中小企業、民間企業から行政まで、海外展開に必要なサービスをワンストップで支援しております。海外マーケティングセールスからデジタルマーケティング、多言語サイトや越境ECサイト制作等の海外向けクリエイティブ制作、グローバル人材採用支援まで幅広く対応しております。お気軽にお問い合わせください。

Check Also

PHP/Laravel モデルの作成

■下準備 事前の準備として、フ …