LoginSignup
0
0

More than 3 years have passed since last update.

Laravel NovaのCardやActionで自作クラスを作らずにインスタンス化する

Posted at

Laravel NovaのCardやAction, Filter、Partitionですが、基本的には自作クラスを作る必要があります。

image.png

カードの作成例
$ php artisan nova:card acme/analytics

AnalyticsCar.php
<?php

namespace Acme\Analytics;

use Laravel\Nova\Card;

class Analytics extends Card
{
    /**
     * The width of the card (1/3, 1/2, or full).
     *
     * @var string
     */
    public $width = '1/3';

    /**
     * Indicates that the analytics should show current visitors.
     *
     * @return $this
     */
    public function currentVisitors()
    {
        return $this->withMeta(['currentVisitors' => true]);
    }

    /**
     * Get the component name for the card.
     *
     * @return string
     */
    public function component()
    {
        return 'analytics';
    }
}

こうして作ったクラスをリソースに登録します。

Analitcs.php(リソース)

...
public function cards(Request $request)
{
    return [new Analytics];
}
...

作成 -> 登録が面倒な場合には無名クラスを使うと便利です。

Analitcs.php(リソース)
public function cards(Request $request)
{
    return [
       (new class extends Card {
              public $width = '1/3';
              public function currentVisitors()
              {
                 return $this->withMeta(['currentVisitors' => true]);
              }
       ),
   ];
}

こうすることでクラスを作らなくともいきなりカードの登録ができます。

インスタンスからメソッドの呼び出しも可能です。

Analitcs.php(リソース)
public function cards(Request $request)
{
    return [
       (new class extends Card {
              public $width = '1/3';
              public function currentVisitors()
              {
                 return $this->withMeta(['currentVisitors' => true]);
              }
       )->currentVisitors(),
   ];
}

複数のリソースをまたがったりする場合にはクラスを作ったほうが良いですが、ちょっとカードを使いたいときは無名クラスが便利です。

0
0
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
0
0