LoginSignup
160
187

More than 3 years have passed since last update.

【Laravel】Viewのbladeの書き方

Last updated at Posted at 2017-10-27

追記:2019/06/13
Laravel5.5Laravel5.6系でも動作確認済み

個人的にはCakeのHTMLヘルパーより使いやすかな~~て感じします。

if文

index.php
@if ($val === null)
    <p>NULLだよ</p>
@else 
    <p>NULLじゃないよ</p>
@endif

for文

index.php
@for ($i = 1; $i < 10 ; $i++)
    <p>{{ $i }} 番目</p>
@endfor

js呼び出し

index.php
<!-- viewsから見たアドレスを書く views/common/_script.blade.php-->
@include('common._script')

この_script.blade.phpの中にscriptを書く
例:

_script.blade.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    // jsのコード
});
</script>

PHPのClass読み込み

index.php
<!-- 第一引数はbladeで使うためのオブジェクト名第二引数はパス -->
@inject('value_generator', 'App\Libs\ValueGenerator')

CSRFトークン

フォームがある場合はこれをフォーム要素内に記述しないとTokenMismatchExceptionが発生する
【Laravel】TokenMismatchExceptionが発生する原因 - Qiita

index.php
{{ csrf_field() }}

PUTメソッド

更新処理を行う場合に必要

index.php
{{ method_field('PUT') }}

以下使用例

<form method="POST" action="{{ route('users.update', ['id' => $user->id]) }}">
    {{ csrf_field() }}
    {{ method_field('PUT') }}

    // 更新対象なデータ

    <button type="submit">編集する</button>
</form>

DELETEメソッド

削除処理を行う場合に必要

index.php
{{ method_field('DELETE') }}

以下使用例

<form method="POST" action="{{ route('users.destroy', ['id' => $user->id]) }}">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <button type="submit">削除する</button>
</form>

改行して表示

※eはエスケープ処理です

index.php
{!! nl2br(e( $comment )) !!}

共通のテンプレート内に呼び出して表示させる

例:親テンプレートの@yield('content')に子のコンテンツを表示させる場合

親(例:views/layouts/mypage.blade.php)

index.php
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>@yield('title')</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        @yield('content')
    </body>
</html>

子(例:views/mypages/index.blade.php)

index.php
<!-- 親テンプレート -->
@extends('layouts.mypage')

@section('title', 'ページタイトル')

<!-- 親テンプレートに表示させる場所 -->
@section('content')
    <div class="content">コンテンツ</div>
@endsection

ブレードテンプレート実装例

とりあえずこんな感じに書いておけば柔軟に対応できるはず・・・という実装例

親(共通)テンプレート

以下が親(共通)テンプレート例

layouts/app.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>
    {{-- 個別のjavaScript読み込み --}}
    @yield('javascript-head')

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    {{-- 個別のCSS読み込み --}}
    @yield('css')
</head>
<body>
    <div id="app">
        <main class="py-4">
            {{-- コンテンツ部分読み込み --}}
            @yield('content')
        </main>
    </div>

    {{-- 個別のjavaScript読み込み --}}
    @yield('javascript-footer')

</body>
</html>

子テンプレート

以下が子テンプレート(ここではユーザー登録画面)の実装例

users/create.blade.php
@extends('layouts.app')

@section('css')
{{-- この場所に画面毎のcssを記述する --}}

@endsection

@section('javascript-head')
{{-- この場所に画面毎(ヘッダ位置)のjsを記述する --}}

@endsection

@section('content')

<form action="{{ route('users.store') }}" method="post">
{{ csrf_field() }}
    <div>
        <!-- エラーメッセージ -->
        @if(count($errors) > 0)
            <div class="error_message">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <table>
            <tbody>
                <tr>
                    <th scope="row">名前<span>必須</span></th>
                    <td><input type="text" id="name" name="name"></td>
                </tr>
                <tr>
                    <th scope="row">メールアドレス<span>必須</span></th>
                    <td><input type="text" id="email" name="email"></td>
                </tr>
                <tr>
                    <th scope="row">パスワード<span>必須</span></th>
                    <td><input type="password" id="password" name="password"></td>
                </tr>
            </tbody>
        </table>
    </div>
    <button type="submit" id="confirm" name="confirm">確認画面へ</button>
</form>
@endsection

@section('javascript-footer')
{{-- この場所に画面毎(フッタ位置)のjsを記述する --}}

@endsection

Sessionの表示

index.php
@if(Session::has('message'))
    <div class="error_message">
        <p>{{ session('message') }}</p>
    </div>
@endif

以下も参考になるかもしれません

PHPのコードを記述する

index.php
@php
    echo 'hello';
@endphp

ただし公式からの注意

Tip!! Bladeはこの機能を提供していますが、数多く使用しているのであれば、それはテンプレートへ多すぎるロジックを埋め込んでいるサインです。

コメントアウト

HTMLソースには表示されません

index.php
{{-- コメント --}}

参考

おわり

以下もどうぞ

160
187
1

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
160
187