LoginSignup
2
3

More than 1 year has passed since last update.

今更ながらLaravel8.xのComponentを使う

Posted at

今更ながらLaravel8.xを触ってみたりしたので、忘備録として。

6.x以前の話

6.x以前は@componentディレクティブを利用してコンポーネントを読み込んでた方も多かったと思います。

xxx.blade.php
@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

第二引数で値を渡して、@ifとかの条件分岐でモギモギする感じでしたね。

Component作成コマンドの追加

7以降では新たに以下のコマンドが追加されています。

php artisan make:component Alert
# サブディレクトリに配置する場合は「/」で区切る
php artisan make:component Common/Alert

このコマンドを利用した場合、コンポーネントのbladeテンプレートはresources/views/components以下に配置されます。
また、app/View/Components内にAlertコンポーネントクラスファイルが配置されます。

試しにコンポーネントを作成する

とりあえずどこかの掲示板のコメントを想定して作ってみます。

  • お名前
  • コメント
  • メルアド(空白可)

の3つのパラメーターを持つコンポーネントを作成してみます。

make:componentコマンドの実行

ArtisanコマンドでCommentItemコンポーネントを作成します。
この時点ではパラメーターが追加されていないので、
コンポーネントクラスにいろいろ書き加えにいきます。

php artisan make:component CommentItem

コンポーネントクラスにパラメーターの追加

__constructに受け取る変数を追記します。
いずれも文字列なのでString型で受け取り、メンバ変数として保存。
Null許容のメールアドレスのみ、nullableにします。

app\View\Components\CommentItem.php
<?php

namespace App\View\Components;

use Illuminate\View\Component;

class CommentItem extends Component
{
    public String $name;
    public String $comment;
    public ?String $mailAddress;

    public function __construct(String $name, String $comment, ?String $mailAddress)
    {
        $this->name= $name;
        $this->comment = $comment;
        $this->mailAddress = $mailAddress;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.comment-item');
    }
}

コンポーネントViewの修正

メールアドレスがあれば名前にリンクを付けるような形式にします。
コメントはそのまま表示。

@if ($mailAddress)
<p><a href="mailto:{{ $mailAddress }}">{{ $name }}</a></p>
@else 
<p>{{ $name }}</p>
@endif
<p>{{ $comment }}</p>

コンポーネントの呼び出し

<x-(コンポーネント名) [(パラメーター名)=(値)]>
みたいな形式でbladeテンプレートに追記することで、コンポーネントの呼び出しが可能です。

<x-commentItem name="山田太郎" comment="こんにちにゃ!" mail-address="sample@example.com" />
<x-commentItem name="山田二郎" comment="こんばんにゃ!" />

これでコンポーネントの呼び出しまで出来るようになったかと思います。

その他

動的コンポーネントなど便利なものもあるようですが、今回は扱わないのでreadoubleにて。。

ちら裏

pugやらvueやらの影響を受けてこのような書き方になったのでしょうか。。
フロントエンジニア視点で作りやすくなっていれば良いのですが。。

2
3
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
2
3