LoginSignup
84
116

More than 5 years have passed since last update.

【Laravel入門】コントローラの作成とビュー表示

Last updated at Posted at 2018-04-29

コントローラの作成

今回は、コントローラの作成からビューへの変数・配列の受け渡しまでやってみる。

ますはコントローラを作成しよう。お決まりの"Hello,World!"を表示させたいので、名前はHelloControllerにする。

$ php artisan make:controller HelloController
Controller created successfully.

成功すると、app/Http/ControllersHelloController.phpが作成されているはずだ。そこにpublic function index ()以下の部分を追記する。

HelloController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HelloController extends Controller
{
    public function index () 
    {
        $hello = 'Hello,World!';
        $hello_array = ['Hello', 'こんにちは', 'ニーハオ'];

        return view('index', compact('hello', 'hello_array'));
    }

}

動作の流れはこうだ。compactメソッドを使えば、ビューに変数と配列を渡すことができる。この場合、変数や配列であっても$を表記しないことに注意しよう。

  • indexアクションを作成する。
  • 変数$hello配列$hello_arrayを定義する。
  • viewメソッドで、compactメソッドで渡された内容を含んだindex.blade.phpを表示する。

ルーティングの設定

次はルーティングの設定だ。次の一文を追記する。

routes/web.php
Route::get('/index', 'HelloController@index');

これで/indexでアクセスされた時に、HelloControllerのindexアクションが実行される。

Bladeビューの作成

今回は動作確認をするだけなので、おさらいも兼ねてlayout.blade.phpを親ビューとするindex.blade.phpを作成することにする。

【Laravel入門】ビューとBladeと継承

resources/views/index.blade.php
@extends('common.layout')

@section('index')
    <p>{{ $hello }}</p>
    @foreach ($hello_array as $hello_word)
        {{ $hello_word }}<br>
    @endforeach
@endsection

親ビューへの記載もお忘れなく。

resources/views/common/layout.blade.php
@yield('index')

BladeはHTMLの書き方がベースにあるが、PHPの記述も直接可能だ。そのため、2つの記法がごちゃ混ぜにならないように注意したい。

変数の記述

{{ $変数名 }}で出力が可能だ。変数を{{ }}で括る理由もちゃんとある。

公式ドキュメントより(一部抜粋)

Bladeの{{ }}記法はXSS攻撃を防ぐため、自動的にPHPのhtmlspecialchars関数を通されます。

とっても便利。

配列の記述

ここで一例として@foreachディレクティブを使ってみる。

まず、PHPのforeach文なら通常こう記述するだろう。

example.php
<?php
foreach ($hello_array as $hello_word) {
    echo $hello_word."<br>";
}
?>

上記の構文を@foreachディレクティブとしてBladeビューに記述する時は、ここが違う。

  • 変数の出力にechoはいらない。
  • 変数は{{ $変数名 }}で記述する。
  • 改行する場合は."<br>"ではなく直接<br>と記述する。
  • 末尾の;はいらない。
  • {}ではなく、@foreach〜@endforeachで括る。

しかし、実際書いてみるとHTMLファイルの中で<?php〜?>と括って記述していた時よりも、ずっと楽だった。

ディレクティブには様々な種類があるそうので、随時活用していきたい。

今回はここまで。

84
116
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
84
116