Readouble

Laravel 9.x フロントエンド

イントロダクションIntroduction

Laravelは、ルーティングバリデーションキャッシュ, キュー, ファイルストレージなど、最新のウェブアプリケーション構築に必要となる全ての機能が提供されているバックエンド・フレームワークです。しかし、私たちはアプリケーションのフロントエンドを構築するための強力なアプローチを含む、美しいフルスタック体験を開発者に提供することも重要であると考えています。Laravel is a backend framework that provides all of the features you need to build modern web applications, such as routing[/docs/{{version}}/routing], validation[/docs/{{version}}/validation], caching[/docs/{{version}}/cache], queues[/docs/{{version}}/queues], file storage[/docs/{{version}}/filesystem], and more. However, we believe it's important to offer developers a beautiful full-stack experience, including powerful approaches for building your application's frontend.

Laravelでアプリケーションを構築する場合、フロントエンドの開発には主に2つの方法があります。どちらの方法を選択するかは、PHPを活用してフロントエンドを構築するか、VueやReactなどのJavaScriptフレームワークを使用するかにより決まります。以下では、こうした選択肢について説明し、あなたのアプリケーションに最適なフロントエンド開発のアプローチの情報を十分に得た上で、決定してもらえるようにします。There are two primary ways to tackle frontend development when building an application with Laravel, and which approach you choose is determined by whether you would like to build your frontend by leveraging PHP or by using JavaScript frameworks such as Vue and React. We'll discuss both of these options below so that you can make an informed decision regarding the best approach to frontend development for your application.

PHPの使用Using PHP

PHPとBladePHP & Blade

以前、ほとんどのPHPアプリケーションでは、リクエスト時にデータベースから取得したデータを表示するため、PHPのecho文を散りばめた単純なHTMLテンプレートを使用し、ブラウザでHTMLをレンダしていました。In the past, most PHP applications rendered HTML to the browser using simple HTML templates interspersed with PHP echo statements which render data that was retrieved from a database during the request:

<div>
    <?php foreach ($users as $user): ?>
        Hello, <?php echo $user->name; ?> <br />
    <?php endforeach; ?>
</div>

このHTML表示の手法を使う場合、LaravelではビューBladeを使用して実現できます。Bladeは非常に軽量なテンプレート言語で、データの表示や反復処理などに便利な、短い構文を提供しています。In Laravel, this approach to rendering HTML can still be achieved using views[/docs/{{version}}/views] and Blade[/docs/{{version}}/blade]. Blade is an extremely light-weight templating language that provides convenient, short syntax for displaying data, iterating over data, and more:

<div>
    @foreach ($users as $user)
        Hello, {{ $user->name }} <br />
    @endforeach
</div>

この方法でアプリケーションを構築する場合、フォーム送信や他のページへの操作は、通常サーバから全く新しいHTMLドキュメントを受け取り、ページ全体をブラウザで再レンダします。現在でも多くのアプリケーションは、シンプルなBladeテンプレートを使い、この方法でフロントエンドを構築するのが、最も適していると思われます。When building applications in this fashion, form submissions and other page interactions typically receive an entirely new HTML document from the server and the entire page is re-rendered by the browser. Even today, many applications may be perfectly suited to having their frontends constructed in this way using simple Blade templates.

高まる期待Growing Expectations

しかし、Webアプリケーションに対するユーザーの期待値が高まるにつれ、多くの開発者がよりダイナミックなフロントエンドを構築し、洗練した操作性を感じてもらう必要性を感じてきています。そのため、VueやReactといったJavaScriptフレームワークを用いた、アプリケーションのフロントエンド構築を選択する開発者もいます。However, as user expectations regarding web applications have matured, many developers have found the need to build more dynamic frontends with interactions that feel more polished. In light of this, some developers choose to begin building their application's frontend using JavaScript frameworks such as Vue and React.

一方で、自分が使い慣れたバックエンド言語にこだわる人たちは、そのバックエンド言語を主に利用しながら、最新のWebアプリケーションUIの構築を可能にするソリューションを開発しました。たとえば、Rails のエコシステムでは、Turbo や[Hotwire]、Stimulus などのライブラリ作成が勢いづいています。Others, preferring to stick with the backend language they are comfortable with, have developed solutions that allow the construction of modern web application UIs while still primarily utilizing their backend language of choice. For example, in the Rails[https://rubyonrails.org/] ecosystem, this has spurred the creation of libraries such as Turbo[https://turbo.hotwired.dev/] Hotwire[https://hotwired.dev/], and Stimulus[https://stimulus.hotwired.dev/].

Laravelのエコシステムでは、主にPHPを使い、モダンでダイナミックなフロントエンドを作りたいというニーズから、Laravel LivewireAlpine.jsが生まれました。Within the Laravel ecosystem, the need to create modern, dynamic frontends by primarily using PHP has led to the creation of Laravel Livewire[https://laravel-livewire.com] and Alpine.js[https://alpinejs.dev/].

LivewireLivewire

Laravel Livewireは、VueやReactといったモダンなJavaScriptフレームワークで作られたフロントエンドのように、ダイナミックでモダン、そして生き生きとしたLaravelで動作するフロントエンドを構築するためのフレームワークです。Laravel Livewire[https://laravel-livewire.com] is a framework for building Laravel powered frontends that feel dynamic, modern, and alive just like frontends built with modern JavaScript frameworks like Vue and React.

Livewireを使用する場合、レンダし、アプリケーションのフロントエンドから呼び出したり操作したりできるメソッドやデータを公開するUI部分をLivewire「コンポーネント」として作成します。例えば、シンプルな"Counter"コンポーネントは、以下のようなものです。When using Livewire, you will create Livewire "components" that render a discrete portion of your UI and expose methods and data that can be invoked and interacted with from your application's frontend. For example, a simple "Counter" component might look like the following:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Counter extends Component
{
    public $count = 0;

    public function increment()
    {
        $this->count  ;
    }

    public function render()
    {
        return view('livewire.counter');
    }
}

そして、このCounterに対応するテンプレートは、次のようになります。And, the corresponding template for the counter would be written like so:

<div>
    <button wire:click="increment"> </button>
    <h1>{{ $count }}</h1>
</div>

ご覧の通り、Livewireでは、Laravelアプリケーションのフロントエンドとバックエンドをつなぐ、wire:clickのような新しいHTML属性を書けます。さらに、シンプルなBlade式を使って、コンポーネントの現在の状態をレンダできます。As you can see, Livewire enables you to write new HTML attributes such as wire:click that connect your Laravel application's frontend and backend. In addition, you can render your component's current state using simple Blade expressions.

多くの人にとって、LivewireはLaravelでのフロントエンド開発に革命を起こし、Laravelの快適さを保ちながら、モダンでダイナミックなWebアプリケーションを構築することを可能にしました。通常、Livewireを使用している開発者は、Alpine.jsも利用して、ダイアログウィンドウのレンダーなど、必要な場合にのみフロントエンドにJavaScriptを「トッピング」します。For many, Livewire has revolutionized frontend development with Laravel, allowing them to stay within the comfort of Laravel while constructing modern, dynamic web applications. Typically, developers using Livewire will also utilize Alpine.js[https://alpinejs.dev/] to "sprinkle" JavaScript onto their frontend only where it is needed, such as in order to render a dialog window.

Laravelに慣れていない方は、ビューBladeの基本的な使い方に、まず慣れることをお勧めします。その後、公式のLaravel Livewireドキュメントを参照し、インタラクティブなLivewireコンポーネントでアプリケーションを次のレベルに引き上げる方法を学んでください。If you're new to Laravel, we recommend getting familiar with the basic usage of views[/docs/{{version}}/views] and Blade[/docs/{{version}}/blade]. Then, consult the official Laravel Livewire documentation[https://laravel-livewire.com/docs] to learn how to take your application to the next level with interactive Livewire components.

スターターキットStarter Kits

PHPとLivewireを使ってフロントエンドを構築したい場合、BreezeまたはJetstreamのスターターキットを活用して、アプリケーション開発を迅速に開始できます。これらのスターターキットは、BladeTailwindを使って、アプリケーションのバックエンドおよびフロントエンドの認証フローに対するスカフォールドを生成するため、次回に開発する皆さんの大きなアイデアの構築を簡単に開始できます。If you would like to build your frontend using PHP and Livewire, you can leverage our Breeze or Jetstream starter kits[/docs/{{version}}/starter-kits] to jump-start your application's development. Both of these starter kits scaffold your application's backend and frontend authentication flow using Blade[/docs/{{version}}/blade] and Tailwind[https://tailwindcss.com] so that you can simply start building your next big idea.

Vue/Reactの使用Using Vue / React

LaravelやLivewireを使用してモダンなフロントエンドを構築することは可能ですが、多くの開発者はVueやReactなどのJavaScriptフレームワークのパワーを活用することをまだ好んでいます。このため、開発者はNPMを使い、利用可能なJavaScriptパッケージやツールの豊富なエコシステムを活用できます。Although it's possible to build modern frontends using Laravel and Livewire, many developers still prefer to leverage the power of a JavaScript framework like Vue or React. This allows developers to take advantage of the rich ecosystem of JavaScript packages and tools available via NPM.

しかし、LaravelとVueやReactを組み合わせるには、クライアントサイドのルーティング、データハイドレーション、認証など、様々な複雑な問題を解決する必要があり、追加のツールがなければLaravelを使うことはできません。クライアントサイドのルーティングは、NuxtNextなど主義的なVue/Reactフレームワークを取り入れて簡素化されていることが多いですが、Laravelなどのバックエンドフレームワークとこれらのフレームワークを組み合わせる場合、データのハイドレートと認証で、複雑で面倒な問題が残ります。However, without additional tooling, pairing Laravel with Vue or React would leave us needing to solve a variety of complicated problems such as client-side routing, data hydration, and authentication. Client-side routing is often simplified by using opinionated Vue / React frameworks such as Nuxt[https://nuxtjs.org/] and Next[https://nextjs.org/]; however, data hydration and authentication remain complicated and cumbersome problems to solve when pairing a backend framework like Laravel with these frontend frameworks.

さらに、開発者は2つの別々のコードリポジトリを管理することになり、しばしばメンテナンス、リリース、デプロイメントを両方のリポジトリにまたがって調整する必要が起きます。こうした問題は克服できないものではありませんが、アプリケーションを開発する上で、生産的で楽しい方法とは思えません。In addition, developers are left maintaining two separate code repositories, often needing to coordinate maintenance, releases, and deployments across both repositories. While these problems are not insurmountable, we don't believe it's a productive or enjoyable way to develop applications.

InertiaInertia

幸運にも、Laravelは両方の世界の最良を提供しています。Inertiaは、LaravelアプリケーションとモダンなVueまたはReactフロントエンドの間のギャップを埋めるもので、VueやReactを使って本格的でモダンなフロントエンドを構築しながら、ルーティング、データハイドレート、認証にLaravelルートとコントローラを活用できます。すべて単一のコードリポジトリ内で行えます。このアプローチではどちらのツールの能力も損なうことなく、LaravelとVue/Reactの両能力を享受することができます。Thankfully, Laravel offers the best of both worlds. Inertia[https://inertiajs.com] bridges the gap between your Laravel application and your modern Vue or React frontend, allowing you to build full-fledged, modern frontends using Vue or React while leveraging Laravel routes and controllers for routing, data hydration, and authentication — all within a single code repository. With this approach, you can enjoy the full power of both Laravel and Vue / React without crippling the capabilities of either tool.

LaravelアプリケーションにInertiaをインストールしたあとで、通常通りにルートとコントローラを記述します。しかし、コントローラからBladeテンプレートを返すのではなく、Inertiaページを返すようにします。After installing Inertia into your Laravel application, you will write routes and controllers like normal. However, instead of returning a Blade template from your controller, you will return an Inertia page:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\User;
use Inertia\Inertia;

class UserController extends Controller
{
    /**
     * 指定ユーザーのプロフィールページを表示
     *
     * @param  int  $id
     * @return \Inertia\Response
     */
    public function show($id)
    {
        return Inertia::render('Users/Profile', [
            'user' => User::findOrFail($id)
        ]);
    }
}

Inertiaページは、VueまたはReactコンポーネントに対応し、通常アプリケーションのresources/js/Pagesディレクトリに格納します。Inertia::renderメソッドにより、ページに与えたデータは、ページコンポーネントの"props"をハイドレートするために使用されます。An Inertia page corresponds to a Vue or React component, typically stored within the resources/js/Pages directory of your application. The data given to the page via the Inertia::render method will be used to hydrate the "props" of the page component:

<script setup>
import Layout from '@/Layouts/Authenticated.vue';
import { Head } from '@inertiajs/inertia-vue3';

const props = defineProps(['user']);
</script>

<template>
    <Head title="User Profile" />

    <Layout>
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Profile
            </h2>
        </template>

        <div class="py-12">
            Hello, {{ user.name }}
        </div>
    </Layout>
</template>

ご覧の通り、Inertiaを使うことで、Laravelを使ったバックエンドと、JavaScriptを使ったフロントエンドの間の軽量なブリッジが提供され、フロントエンドを構築する際にVueやReactのパワーをフル活用することができます。As you can see, Inertia allows you to leverage the full power of Vue or React when building your frontend, while providing a light-weight bridge between your Laravel powered backend and your JavaScript powered frontend.

サーバサイドレンダServer-Side Rendering

アプリケーションでサーバサイドレンダが必要なため、Inertiaに飛び込むことを躊躇している方も、安心してください。Inertiaはサーバサイドレンダリングサポートを提供しています。また、Laravel Forgeを介してアプリケーションをデプロイする場合、Inertiaのサーバサイドレンダリングプロセスが常に実行されていることを簡単に確認できます。If you're concerned about diving into Inertia because your application requires server-side rendering, don't worry. Inertia offers server-side rendering support[https://inertiajs.com/server-side-rendering]. And, when deploying your application via Laravel Forge[https://forge.laravel.com], it's a breeze to ensure that Inertia's server-side rendering process is always running.

スターターキットStarter Kits

InertiaとVue/Reactを使用してフロントエンドを構築したい場合は、BreezeまたはJetstreamのスターターキットを活用して、アプリケーション開発を迅速に開始できます。これらのスターターキットは、Inertia、Vue/React、TailwindViteを使用してアプリケーションのバックエンドとフロントエンドでの認証フローに必要なスカフォールディングを生成するため、次に開発する皆さんの大きなアイデアをすぐに構築開始できます。If you would like to build your frontend using Inertia and Vue / React, you can leverage our Breeze or Jetstream starter kits[/docs/{{version}}/starter-kits#breeze-and-inertia] to jump-start your application's development. Both of these starter kits scaffold your application's backend and frontend authentication flow using Inertia, Vue / React, Tailwind[https://tailwindcss.com], and Vite[https://vitejs.dev] so that you can start building your next big idea.

アセットの結合Bundling Assets

BladeとLivewire、Vue/ReactとInertiaのどちらを使用してフロントエンドを開発するにしても、アプリケーションのCSSをプロダクション用アセットへバンドルする必要があるでしょう。もちろん、VueやReactでアプリケーションのフロントエンドを構築することを選択した場合は、コンポーネントをブラウザ用JavaScriptアセットへバンドルする必要があります。Regardless of whether you choose to develop your frontend using Blade and Livewire or Vue / React and Inertia, you will likely need to bundle your application's CSS into production ready assets. Of course, if you choose to build your application's frontend with Vue or React, you will also need to bundle your components into browser ready JavaScript assets.

Laravelは、デフォルトでViteを利用してアセットをバンドルします。Viteは、ローカル開発において、ビルドが非常に速く、ほぼ瞬時のホットモジュール交換(HMR)を提供しています。スターターキットを含むすべての新しいLaravelアプリケーションでは、vite.config.jsファイルがあり、軽量なLaravel Viteプラグインがロードされ、LaravelアプリケーションでViteを楽しく使用できるようにしています。By default, Laravel utilizes Vite[https://vitejs.dev] to bundle your assets. Vite provides lightning-fast build times and near instantaneous Hot Module Replacement (HMR) during local development. In all new Laravel applications, including those using our starter kits[/docs/{{version}}/starter-kits], you will find a vite.config.js file that loads our light-weight Laravel Vite plugin that makes Vite a joy to use with Laravel applications.

LaravelとViteを使い始める最も早い方法は、Laravel Breezeを使ってアプリケーションの開発を始めることです。これは、フロントエンドとバックエンドで認証に必要なスカフォールドを生成してくれます。アプリケーション開発をロケットスタートする、最もシンプルなスターターキットです。The fastest way to get started with Laravel and Vite is by beginning your application's development using Laravel Breeze[/docs/{{version}}/starter-kits#laravel-breeze], our simplest starter kit that jump-starts your application by providing frontend and backend authentication scaffolding.

lightbulb Note:LaravelでViteを活用するための詳細なドキュメントは、アセットバンドルとコンパイルに関する専用のドキュメントを参照してください。Note
For more detailed documentation on utilizing Vite with Laravel, please see our dedicated documentation on bundling and compiling your assets[/docs/{{version}}/vite].

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作