【Laravel】artisanのmake:componentコマンドを解説

チートシート

Laravel 10.x以降のartisanの「make:component」コマンドを解説します。

Description

新しいビューコンポーネントクラスを作成します。

Usage

php artisan make:component [-f|--force] [--inline] [--view] [--] <name>

Arguments

引数必須説明
name必須コンポーネント名

Options

オプション省略形必須説明
forceコンポーネントが既に存在する場合でもクラスを作成する
inlineインラインビューをレンダリングするコンポーネントを作成する
viewビューだけを持つ匿名コンポーネントを作成する

Examples

no options

php artisan make:component Foo
   INFO  Component [app/View/Components/Foo.php] created successfully.  
<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class Foo extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return view('components.foo');
    }
}
<div>
    <!-- Simplicity is an acquired taste. - Katharine Gerould -->
</div>

bladeの中身のコメントアウトにinspireが入っているのが良いですね。

inline

php artisan make:component --inline Foo
   INFO  Component [app/View/Components/Foo.php] created successfully.  
<?php

namespace App\View\Components;

use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;

class Foo extends Component
{
    /**
     * Create a new component instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|Closure|string
    {
        return <<<'blade'
<div>
    <!-- Simplicity is the ultimate sophistication. - Leonardo da Vinci -->
</div>
blade;
    }
}

view

php artisan make:component --view Foo
   INFO  Component created successfully.  
<div>
    <!-- I begin to speak only when I am certain what I will say is not better left unsaid. - Cato the Younger -->
</div>

Stub

OptionStub file name
view-component.stub

Source

著者

Webエンジニア歴30年、フリーランスバックエンドエンジニア。

PHP歴約30年(Laravel 7年・FuelPHP 5年・CakePHP・自作FW)、
JavaScript歴約20年(React・Vue各4年)。
AWS(EC2 / CloudFront / RDS / API Gateway など)・
GCP(BigQuery)を使ったバックエンド開発を中心に、
複数の事業会社・受託案件でシステム設計から実装・運用まで担当しています。

PHPがバージョン4の時代から書いており、
Laravelが普及する前のフレームワーク乱立期も経験しています。
「昔はこう書いていたが今はこう」という変遷を肌で知っているエンジニアとして、
単なるコマンドの使い方だけでなく、なぜそうするのかの背景まで伝えることを意識して書いています。

このブログでは、実務で実際に詰まった箇所・調べたこと・気づいたことを
そのまま記事にしています。誰かの「詰まり」が解決するきっかけになれば幸いです。

千原 耕司をフォローする

役にたったと思ったら応援をお願いします m(._.)m

チートシート
スポンサーリンク
シェアする
千原 耕司をフォローする
タイトルとURLをコピーしました