Search code examples
phplaravellaravel-nova

Use Laravel Events/Listener with Nova buttons


I would like to use the https://github.com/dillingham/nova-button module but in its example it shows how to use the button with an event but only shows its listener. I have trouble understanding how he defines his key.

Here's my listener:

<?php

namespace App\Listeners;

use App\Events\DeleteProduct;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class DeleteProductListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  DeleteProduct  $event
     * @return void
     */
    public function handle(DeleteProduct $event)
    {
        if ($event->key == 'mark-as-confirmed') {
            $event->resource->status = 1;
            $event->resource->save();
        }
    }
}

Here's my Nova Field:

Button::make('Supprimer', 'mark-as-confirmed')
                ->event('App\Events\DeleteProduct')
                ->confirm('Êtes vous sûr de vouloir supprimer ce produit?')
                ->loadingText('Suppression...')
                ->successText('Supprimé!')

And here's my error when I click on the button:

Error

How do I set my key correctly?


Solution

  • try this:

    modify in your class EventServiceProvider

    protected $listen = [
        '\NovaButton\Events\ButtonClick' => [
            '\App\Listeners\DeleteProductListener'
        ]
    ];
    

    reference: https://github.com/dillingham/nova-button/issues/9#issuecomment-457760978