Search code examples
phplaravelnotificationslumen

Lumen how to pass variable to notification


I'm using the following plugin in my lumen:

"illuminate/notifications": "^8.11",    
"laravel-notification-channels/telegram": "^0.5.0",

After tried many example available online, finally I can send out with the following code set:

    // App/Console/Command/abc.php
    namespace App\Console\Commands;
    
    use NotificationChannels\Telegram\TelegramChannel;
    use NotificationChannels\Telegram\TelegramMessage;
    use Illuminate\Support\Facades\Notification;
    use App\Helpers\TGNotification;
    
     Notification::route(TelegramChannel::class, '-123456')
                                ->notify(new TGNotification($tg));

Above is the code in console command and the below is a helper file:

// App/Helpers/TGNotification.php
namespace App\Helpers;

use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;

class TGNotification extends Notification
{
    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }

    public function toTelegram($notifiable)
    {
        $url = "http://www.google.com";
        return TelegramMessage::create()
            // Optional recipient user id.
            // ->to($notifiable->telegram_user_id)
            ->to("-123456")
            // Markdown supported.
            ->content($notifiable->msg)
            
            // (Optional) Blade template for the content.
            // ->view('notification', ['url' => $url])
            
            // (Optional) Inline Buttons
            ->button('Hello', $url)
            ->button('World', $url);
    }
}

However, I'm not able to pass the variable from abc.php to TGNotification.php. It just don't work if i'm using any example of this plugin available online. Could anyone please advise? Thanks


Solution

  • send your parameter in the construct method:

    class TGNotification extends Notification
    {
        protected $tg;
    
        public function __construct($tg)
        {
            $this->tg = $tg;
        }
    }
    

    or, you can use the setter and getter methods.