7. コンポーネント

コンポーネントの基本

コンポーネントとは

Component(コンポーネント)は部品という意味で、Webアプリケーションでは、HTMLやプログラムを共通化したファイルのことを指します。コンポーネント化することで何度も同じコーディングをせず、効率的に開発ができます。

レイアウトとは

Layout(レイアウト)は、メニューやヘッダーなどの共通部分を1ファイルで構成するコンポーネントファイルです。例えばHTMLのheadタグやbodyタグなどのレイアウトファイルを用意することで、各ページはレイアウト部分をコーディングせずに済みます。

<html>
<head>
<title>Shopping</title>
</head>
<body>
  ページごとのコンテンツを表示
</body>
</html>

Laravelのレイアウト

Laravelのレイアウトの作成方法はいくつかあります。

Blade Components

デフォルトで搭載されているのが Blade Componentsです。

方式 記法例 説明
継承型レイアウト @extends('layouts.app')
@section('content') ... @endsection
従来からある方式。resources/views/layouts に配置したテンプレートを @extends で継承する。
Bladeコンポーネント <x-app-layout> Laravel 7以降の「Bladeコンポーネント」機能を使った方式。resources/views/components に配置したファイルを <x-...> で呼び出す。

Inertia

InertiaReactVueに対応したフロントエンド開発ライブラリで、Laravelバージョン8.x以降で利用できます。

LiveWire

LiveWire は、Laravel 向けの フルスタック・フレームワーク で、 Blade テンプレートだけで SPA(シングルページアプリケーション)風の動きを実現できるツールです。

Vite

Viteとは

Vite」は、VueをはじめとするJavaScriptフレームワークやライブラリ開発にのビルドツールです。

@vite()

@viteディレクティブはBladeテンプレート内でJavaScriptモジュールをロードできます。

@vite(['resources/css/app.css', 'resources/js/app.js'])

Blade Components

方式 説明
Blade継承型レイアウト 従来からある方式で、resources/views/layouts に配置したテンプレートを @extends で継承する。
Bladeコンポーネントレイアウト Laravel 7以降の「Bladeコンポーネント」機能を使った方式で、resources/views/components に配置したファイルを <x-...> で呼び出す。

Blade Componentsレイアウト

レイアウトファイル作成

app.blade.php などのレイアウトファイルを作成します。

レイアウト名.blade.php

ページコンポーネント

Blade Components では、各コンポーネントでレイアウトを x-レイアウト名-layout として利用します。

<x-レイアウト名-layout>
     <!-- コンテンツを記述 -->
</x-レイアウト名-layout>

layouts/app.balde.php の場合

resouces/views/layouts/app.balde.php がレイアウトファイルです。

resouces/views/layouts/app.balde.php
<x-app-layout>
    <div>コンテンツ</div>
</x-app-layout>

App/View/Comopnents/AppLayout.php をからレイアウトファイルを読み込みます。

App/View/Comopnents/AppLayout.php
<?php

namespace App\View\Components;

use Illuminate\View\Component;
use Illuminate\View\View;

class AppLayout extends Component
{
    public function render(): View
    {
        return view('layouts.app');
    }
}

レイアウト作成

ファイル構成

/
├── home/
│   ├── index.blade.php
│   └── about.blade.php
├── product/
│   ├── show.blade.php
│   └── search.blade.php
├── components/
│   ├── nav-menu.blade.php
│   └── main-layout.blade.php

ナビゲーションメニュー作成

ターミナル
php artisan make:component NavMenu

resources/views/components/nav-menu.blade.php が作成されます。

<nav class="bg-gray-800">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
            <div class="flex space-x-4">
                <a href="{{ route('home') }}"
                   class="text-white px-3 py-2 rounded-md text-sm font-medium hover:bg-gray-700">
                    Home
                </a>
                <a href="{{ route('about') }}"
                   class="text-white px-3 py-2 rounded-md text-sm font-medium hover:bg-gray-700">
                    About
                </a>
                <a href="{{ route('products.index') }}"
                   class="text-white px-3 py-2 rounded-md text-sm font-medium hover:bg-gray-700">
                    Product
                </a>
            </div>
        </div>
    </div>
</nav>

MainLayoutレイアウト作成

make:componentMainLayout を作成します。

ターミナル
php artisan make:component MainLayout

ファイル確認

resources/views/components/main-layout.blade.php が作成されます。

resources/views/components/main-layout.blade.php
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $title ?? 'My App' }}</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans antialiased bg-gray-100">
    <header class="bg-white shadow">
        <div class="max-w-7xl mx-auto py-6 px-4 flex justify-between items-center">
            @auth
                <span class="text-gray-700">ようこそ、{{ Auth::user()->name }} さん</span>
            @else
                <span class="text-gray-500">ゲスト</span>
            @endauth

            {{-- ナビゲーション読み込み --}}
            <x-nav />
        </div>
    </header>

    <main class="max-w-7xl mx-auto py-6 px-4">
        {{ $slot }}
    </main>
</body>
</html>

レイアウトの利用

「about」ページ

セクション作成

about.blade.phpから、レイアウト MainLayoutを読み込みます。

about.blade.php
<x-main-layout title="Aboutページ">
    <h1 class="text-xl font-bold mb-4">About</h1>
    <p>これはアバウトページです。</p>
</x-main-layout>

コンテンツが表示されたか確認してみましょう。

結果

コンポーネントフォルダ作成

コンポーネント管理用に「views/components/」フォルダを作成します。

Laravel超入門