Laravel7 レイアウトを共通化する手順
- 作成日 2020.06.07
- 更新日 2020.07.17
- laravel

Laravel7でBladeテンプレートで、レイアウトを共通化する手順を記述してます。
目次
環境
- OS windows10 pro 64bit
- Composer 1.10.5
- PHP 7.4.5
- MariaDB 10.4.12
- Laravel Framework 7.6.2
※windows10に Laravel のインストールはこちら
※windows10に Composer のインストールはこちら
※windows10に PHP のインストールはこちら
※windows10に MariaDB のインストールはこちら
コントローラー作成
「LayouController」という名前でコントローラーを作成します。
php artisan make:controller LayoutController
app/Http/Controllers/ LayoutController.phpが生成されているので、
下記のように編集しておきます。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LayoutController extends Controller
{
public function index() {
return view('layout.index');
}
}
共通レイアウト作成
resources\views\配下にlayoutフォルダを作成し「layout.blade.php」を作成します。
@yield(‘content’)については後述してます。
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>共通レイアウト</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body class="vh-100 d-flex justify-content-center text-center">
<div class="w-75 mt-3">
<div class="text-black-50 text-left border-bottom mt-5">
<h1>共通レイアウト</h1>
</div>
<div>
@yield('content')
</div>
</div>
</body>
</html>
ビュー作成
次にlayoutフォルダ内に「index.blade.php」を下記の内容で作成します。
@extends('layout.layout')
@section('content')
<h2>部分レイアウト</h2>
@endsection
@extends(‘layout.layout’)
利用するレイアウトを指定します。ここではlayoutフォルダ配下の layout.blade.php を利用しているので ‘layout.layout’ と指定してます。
@section(‘content’)
@endsection
共通レイアウトで指定した@yield(‘content’)に埋め込まれる範囲を指定してます。
@yield(‘content’)
sectionの内容を埋め込んで表示する箇所です。
ルーティング追加
アクセスするURLを設定するため、ルーティングを記述します。
routesフォルダ配下にある「web.php」に下記を追加します。
Route::resource('/layout', 'LayoutController');
確認
ブラウザから http://localhost:8000/layout にアクセスしてみて、共通レイアウトである「 layout.blade.php 」が使用できているが確認できます。

-
前の記事
Ubuntu20.04 ArangoDBをインストールする手順 2020.06.06
-
次の記事
Nuxt.js ライブラリ「vue-core-video-player」をインストールして軽量のビデオプレーヤーを実装する 2020.06.08
コメントを書く