Send Laravel notifications to Telegram messenger

Ivan Radunovic

Feb 21, 20245 min read
Send Laravel notifications to Telegram messenger

Sending Telegram notifications from Laravel requires Telegram Notification Channel installed in Laravel.

Installation of Telegram Notification Channel

Use composer to install the package:

composer require laravel-notification-channels/telegram

After this at the bottom of config/services.php add:

'telegram-bot-api' => [
    'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
],

Now we need the token from Telegram and chat ID where we'll send notifications. Chat ID is the identification of the thread in Telegram.

Create Telegram Bot

Find BotFather account inside Telegram and start a thread.

Bot Father

You can type /newbot and it'll guide you through the process of creating new bot.

At the end it'll provide bot token.

Bot Father creating new bot

Take that bot token and insert into .env file.

TELEGRAM_BOT_TOKEN=paste-here-token

Obtain Telegram Chat ID

In this case I created new Telegram Group and added my new bot inside.

New Telegram Group Created

I'll type /heybot message to this group just to start the converation, so I can pickup the ID.

The quickest way to obtain Chat ID is to open Tinker with php artisan tinker and type:

 NotificationChannels\Telegram\TelegramUpdates::create()->limit(10)->options(['timeout' => 0])->get();

If you're seeing empty response like this:

= [
    "ok" => true,
    "result" => [],
  ]

Retry command few times, until it displays /heybot message:

= [
    "ok" => true,
    "result" => [
      [
        "update_id" => 19293881,
        "message" => [
          "message_id" => 4,
          "from" => [
            "id" => 6550505596,
            "is_bot" => false,
            "first_name" => "Ivan",
            "language_code" => "en",
          ],
          "chat" => [
            "id" => -4109128101,
            "title" => "Laravel App",
            "type" => "group",
            "all_members_are_administrators" => true,
          ],
          "date" => 1708516220,
          "text" => "/heybot",
          "entities" => [

From this array inside [result][0][message][chat][id] is the Chat ID we need. In this case it's -4109128101.

Copy this into .env file:

TELEGRAM_CHAT_ID=-4109128101

Laravel Notification Class

Now we need notification class which will use Telegram channel. You can create it with:

php artisan make:notification NewUserRegistered

In this case I decided I'll send notification whenever new user is registered. You can send notification for any event important to you.

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use NotificationChannels\Telegram\TelegramMessage;

class NewUserRegistered extends Notification
{
    use Queueable;

    public function via(object $notifiable): array
    {
        return ['telegram'];
    }

    public function toTelegram($notifiable)
    {
        return TelegramMessage::create()
            ->to(env('TELEGRAM_CHAT_ID'))
            ->content("New user registered")
            ->button('View Profile', 'https://tuts.codingo.me');
    }
}

I put some dummy button there and text. Just to test is it working.

In order to fire this notification I'll use Tinker once more.

 Notification::route('telegram', [])->notify(new App\Notifications\NewUserRegistered());

And it works!

New message from Laravel inside Telegram Group

Send Notification when new user account is created

I'll connect everything now.

First thing is to pass User object to the notification class, so Telegram receives full user name.

<?php

namespace App\Notifications;

use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Bus\Queueable;

class NewUserRegistered extends Notification
{
    use Queueable;

    public $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    public function via(object $notifiable): array
    {
        return ['telegram'];
    }

    public function toTelegram($notifiable)
    {
        return TelegramMessage::create()
            ->to(env('TELEGRAM_CHAT_ID'))
            ->content("New user: " . $this->user->name);
    }
}

Now I need to create Listener which will handle Registered event.

php artisan make:listener NotifyTelegramOfRegistration

Inside Listener I'll send on-demand Telegram notification to the desired Chat ID.

<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Notification;
use App\Notifications\NewUserRegistered;
use Illuminate\Auth\Events\Registered;

class NotifyTelegramOfRegistration
{
    public function handle(Registered $registered): void
    {
        $user = $registered->user;

        Notification::route('telegram', env('TELEGRAM_CHAT_ID'))
            ->notify(new NewUserRegistered($user));
    }
}

The only thing left is registering this new event listerner inside EventServiceProvider

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
            NotifyTelegramOfRegistration::class
        ],
    ];

This is one example how you can use Telegram to receive notification from your Laravel application. With this you can create any kind of notification for any Laravel resource.

Share
Author Photo
Ivan Radunovic is a Senior Developer with over 11 years of experience in web development. His expertise are Laravel SaaS solutions. So far he developed or took part in 300+ Laravel projects.

More Laravel tutorials

Automatically purge Cloudflare Cache on new Deployment

After new deployment and compiling it's important to clear Cloudflare cache, otherwise it'll serve old assets.

Feb 29, 2024 Ivan Radunovic

Cloudflare Turnstile Laravel - Protect your app from bots

Turnstile will protect forms on sites from abusive bots. It's a hassle free alternative for Google ReCaptcha.

Feb 27, 2024 Ivan Radunovic

Login into Laravel application with a Magic link

Magic link authentication is a popular choice for login pages. User can request a link and click on it and he'll be authenticated.

Feb 24, 2024 Ivan Radunovic

Improving Laravel Loading Speed Using Redis Cache

Using Redis with Laravel application should be mandatory in the production. Redis greatly improves performance of Laravel apps if it's implemented in the right way.

Feb 20, 2024 Ivan Radunovic

Laravel SSO authentication with Google One Tap logins

Single sign-on authentication became a standard so we teach you how to implement it in your app. On top of that we'll show you how to integrate Google One Tap authentication flow also.

Feb 13, 2024 Ivan Radunovic

Google ReCaptcha in Laravel - Protect Laravel forms from bots

Learn how to integrate Google ReCAPTCHA into Laravel application, applies for types v2 and v3. All about I'm not a robot checkbox, invisible captcha and score based captcha.

Feb 12, 2024 Ivan Radunovic

Advanced querying with whereHas Method in Laravel Eloquent

The whereHas method in Laravel allows to filter models based on conditions of their related models, simplifying complex queries involving relationships.

Feb 05, 2024 Ivan Radunovic

Soft Delete in Laravel

With Laravel soft delete trait you can mark certain Eloquent model as deleted, and they will be removed from general queries. But you can query them with special methods.

Feb 04, 2024 Ivan Radunovic