LoginSignup
3
3

More than 1 year has passed since last update.

【Laravel8】レイアウト共通化 layoutsファイルのapp.blade.phpのコード例

Last updated at Posted at 2021-08-11

Laravel8でレイアウトを共通化させる方法です。

開発環境
Docker 20.10.7
PHP 7.4.22
Laravel 8.53.1
mySQL 5.7
データベースのツール phpmyadmin
※bootstrapを導入しています。

以下の記事の続きになります。
【Laravel実務に使える】マイグレーションの作成から一覧画面表示まで

本記事のゴール

・親ファイルのレイアウト共通ファイルのコード例
・子テンプレートファイルのコード例
・ファイルを編集したときに出たエラー解消方法

実際にコードを書く

resourcesに共通の親ファイルであるlayoutsファイルを作成し、そこにapp.blade.phpを作成します。

resources
- layouts
-- app.blade.php

app.blade.phpは共通のテンプレートファイルになるので、他のビューファイルでも読み込むことができます。

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>

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

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">

    <!-- Styles -->
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
    <div id="app">
        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

以下のように親ファイルであるapp.blade.phpを継承することができます。

resources>book>index.blade.php

@extends('layouts.app')

@section('content')
<h1>本を管理</h1>

<table class="table table-striped">
  <thead>
    <tr>
      <th>ブックナンバー</th>
      <th>ブック名</th>
      <th>作成日</th>
    </tr>
  </thead>
  <tbody>
    @foreach ($books as $book)
    <tr>
      <td>{{ $book->book_id }}</td>
      <td>{{ $book->book_name }}</td>
      <td>{{ $book->created_at }}</td>
    </tr>
    @endforeach
  </tbody>
</table>
@endsection

私は途中にファイルを作成したりコード内容を変更したせいか以下のようなエラーが出ました。

file_put_contents : failed to open stream: No such file or directory

いくつかの記事を調べると以下で解決しました。

$ php artisan config:cache
$ php artisan config:clear
$ composer dump-autoload -o

キャッシュが原因だったっぽいです。

参考になったらLGTMしてくれると励みになります!

3
3
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
3
3