6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

6
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実務に使える】マイグレーションの作成から一覧画面表示まで

おすすめ技術本の紹介

◯エンジニア基礎力を向上させる前に、AIに頼理すぎてませんか?エンジニアとして一生の基礎力がつくおすすめの技術本を紹介しているので、ぜひ要チェックです!
【AIに頼りすぎではないですか?】エンジニア基礎力を底上げするおすすめ技術書まとめ

本記事のゴール

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

>>>私が運営するブログはこちら。メインは技術ブログですが、副業やポイ活についても紹介!

##実際にコードを書く

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

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

◯エンジニア基礎力を向上させる前に、AIに頼理すぎてませんか?エンジニアとして一生の基礎力がつくおすすめの技術本を紹介しているので、ぜひ要チェックです!
【AIに頼りすぎではないですか?】エンジニア基礎力を底上げするおすすめ技術書まとめ

6
5
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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?