Edward Jackson

Edward Jackson

1588493881

How to Implement and Send Telegram Notifications using Laravel

Telegram is a highly customizable, cloud-based instant messaging service, and It boasts of having over 200+ million active users per month. Even though Telegram is not as widely used as its mammoth competitor WhatsApp, It still manages to provide significant advantages over WhatsApp. Today, I’m going to show you how you can quickly implement and send Telegram Notifications using Laravel.

In this tutorial, we will set up a new Laravel project and send a welcome message via Telegram to any newly registered users in our application.

Telegram Benefits

  • Unlimited Storage: Telegram provides unlimited storage for all your content, including messages, images, media files & documents that will be saved on their cloud without any compression or size limits. This perk comes in handy if your Laravel application needs to send documents or media to its users.
  • Group Member Capacity: Telegram supports groups of up to 5000 members!
  • Bots: Bots in Telegram are based on AI and machine learning. They can perform various tasks. For example, weather bot can fetch weather from your region.
  • Public API: Whatsapp has no open API; however, Telegram provides a free to use, easy to set up public API.

Telegram API Limitations

There is one major limitation to using Telegram’s API. That is to say, Telegram does not allow sending messages directly to the user’s phone numbers unless the user initiates the conversation first!. In short, this is essential for Telegram to prevent spam in the system, but I will show you a workaround to deal with this issue.

Telegram Bot Set-Up

We’ll begin by first creating a bot on Telegram. To do this, Telegram has an official bot called BotFather that can create new bots. Once a bot is created, you will receive an API token, which will be used later in our Laravel application.

Search for BotFather in Telegram application:

The BotFather bot should have a checkmark associated with it. Please refer to the image below and make sure you choose the right bot!

Create a new bot using BotFather :

To create a bot, you need to send the following message to the BotFather bot:

  1. /newbot : Initiate new bot creation with BotFather
  2. You will be asked to give a name for your bot. This is the public name that your users will see.
  3. You will then be asked to provide a username for your bot. This username has to be unique so make sure you give something uncommon and specific to your project.

Finally, you will receive an API token in this process, copy that in a safe location as we will be using it shortly.

Installation and Set-up

Install a new Laravel 7 project:

composer create-project --prefer-dist laravel/laravel laravel-telegram-notifications

Install Laravel’s UI package:

composer require laravel/ui

Generate Laravel’s authentication scaffolding and compile resources:

This will give us Laravel’s default authentication view and you can access user registration at http://your-app/register.

php artisan ui vue --auth
npm install
npm run dev

Also, make sure to run your migrations before you try to register any users.

Install the Telegram Notifications Package:

composer require babenkoivan/telegram-notifications

Register Service Provider:

Register the package’s service provider in config/app.php

// config/app.php
'providers' => [
    ...
    TelegramNotifications\TelegramServiceProvider::class    
]

Publish Package’s Configuration File:

This command will create a telegram.php file in the config directory. We can use this to configure the package.

php artisan vendor:publish --provider='TelegramNotifications\TelegramServiceProvider' 

Set your bot’s API token in .env the file:

TELEGRAM_BOT_TOKEN=your-telegram-api-token

Create a Custom Laravel Notification

Create a custom notification for Telegram messages:

php artisan make:notification LaravelTelegramNotification

The above artisan command creates a LaravelTelegramNotification file in app/Notifications path. Laravel supports sending various types of notifications such as email, SMS, and Slack. Each notification is represented as a Single PHP class located in app/Notifications directory.

Add the telegram message logic to LaravelTelegramNotification.php :

Every notification class must implement a via() method. The telegram package that we use also requires a toTelegram() method to be implemented.

// LaravelTelegramNotification.php
class LaravelTelegramNotification extends Notification
{
    use Queueable;

    protected $data;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(array $arr)
    {
        $this->data = $arr;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toTelegram() {
        return (new TelegramMessage())
            ->text($this->data['text']);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

In the above class, we are creating a dynamic function that accepts a message parameter and sends that message to the user.

Prepare User Model and Registration View

In order to send notifications to Telegram, you need to have the user’s unique User ID. The user_id is a unique identifier of every telegram user and every user can get their user_id by following .

In this tutorial, we will get the Telegram user ID of a user during registration.

Let’s get started by adding user_id to $fillable array in User.php:

// User.php
protected $fillable = [
    'name', 'email', 'password', 'user_id'
];

Define a routeNotificationForTelegram() method in User.php which returns the user’s user_id.

// User.php
/**
 * Return Telegram user_id of the user
 * 
 * @return mixed
 */
public function routeNotificationForTelegram()
{
    return $this->user_id;
}

Add a user_id input field to the user registration form in register.blade.php

// register.blade.php
<div class="form-group row" style="background:lightgray">
    <label for="email" class="col-md-4 col-form-label text-md-right">{{ __('Telegram User Id') }}</label>

    <div class="col-md-6">
        <input id="user_id" class="form-control @error('user_id') is-invalid @enderror" name="user_id" value="{{ old('user_id') }}" required autocomplete="user_id">

        @error('user_id')
        <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

The output should look something like this:

Modify RegisterController.php to account for the new user_id field and we will also be adding the logic for sending the notification to the user in create() method.

// RegisterController.php
/**
 * Get a validator for an incoming registration request.
 *
 * @param  array  $data
 * @return \Illuminate\Contracts\Validation\Validator
 */
protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'user_id' => ['required', 'string', 'max:255'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'user_id' => $data['user_id'],
        'password' => Hash::make($data['password']),
    ]);

    $user->notify(new LaravelTelegramNotification([
        'text' => "Welcome to the application " . $user->name . "!"
    ]));

    return  $user;
}

Sending more than just a message:

You can also send other data using this package. For example, images, videos, documents, contacts, location and audio files. Modify the toTelegram() method to send a collection of messages and send the data during create() method of RegisterController.php.

// LaravelTelegramNotification.php
public function toTelegram() {
    return (new TelegramCollection())
        ->message(['text' => $this->data['text']])
        ->location(['latitude' => $this->data['latitude'], 'longitude' => $this->data['longitude']])
        ->photo(['photo' => $this->data['photo'], 'caption' => $this->data['photo_caption']]);
}
// RegisterController.php
protected function create(array $data)
{

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'user_id' => $data['user_id'],
        'password' => Hash::make($data['password']),
    ]);

    $user->notify(new LaravelTelegramNotification([
        'text' => "Welcome to the application " . $user->name . "!",
        'latitude' => '23.022505',
        'longitude' => '72.571365',
        'photo' => 'https://laravelcode.com/upload/logo.svg',
        'photo_caption' => 'Telegram Notifications in Laravel'
    ]));

    return  $user;
}

Now go ahead and try the user registration by heading to the registration page in a browser. Subsequently, the user should receive a message from your bot!

then you can see your both of messages ini the telegram bots:

That’s it, it’s quite easy to implement Telegram notifications and send Telegram notifications using Laravel! Also, If you have any questions or suggestions, please drop them in the comments section below The complete working Laravel project used for this tutorial can found in my GitHub repository.

#laravel #php #web-development

What is GEEK

Buddha Community

How to Implement and Send Telegram Notifications using Laravel

How to Send E-mail Using Queue in Laravel 7/8

Today I will show you How to Send E-mail Using Queue in Laravel 7/8, many time we can see some process take more time to load like payment gateway, email send, etc. Whenever you are sending email for verification then it load time to send mail because it is services. If you don’t want to wait to user for send email or other process on loading server side process then you can use queue.

Read More : How to Send E-mail Using Queue in Laravel 7/8

https://websolutionstuff.com/post/how-to-send-e-mail-using-queue-in-laravel-7-8


Read Also : Send Mail Example In Laravel 8

https://websolutionstuff.com/post/send-mail-example-in-laravel-8

#how to send e-mail using queue in laravel 7/8 #email #laravel #send mail using queue in laravel 7 #laravel 7/8 send mail using queue #laravel 7/8 mail queue example

Seamus  Quitzon

Seamus Quitzon

1595201363

Php how to delete multiple rows through checkbox using ajax in laravel

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

#laravel #delete multiple rows in laravel using ajax #laravel ajax delete #laravel ajax multiple checkbox delete #laravel delete multiple rows #laravel delete records using ajax #laravel multiple checkbox delete rows #laravel multiple delete

I am Developer

1597487833

Country State City Drop Down List using Ajax in Laravel

Here, i will show you how to create dynamic depedent country state city dropdown list using ajax in laravel.

Country State City Dropdown List using Ajax in php Laravel

Follow Below given steps to create dynamic dependent country state city dropdown list with jQuery ajax in laravel:

  • Step 1: Install Laravel App
  • Step 2: Add Database Details
  • Step 3: Create Country State City Migration and Model File
  • Step 4: Add Routes For Country State City
  • Step 5: Create Controller For Fetch Country State City
  • Step 6: Create Blade File For Show Dependent Country State City in Dropdown
  • Step 7: Run Development Server

https://www.tutsmake.com/ajax-country-state-city-dropdown-in-laravel/

#how to create dynamic dropdown list using laravel dynamic select box in laravel #laravel-country state city package #laravel country state city drop down #dynamic dropdown country city state list in laravel using ajax #country state city dropdown list using ajax in php laravel #country state city dropdown list using ajax in laravel demo

Send Email In Laravel

Hello Guys,

Today I will give you demo how to send email in laravel, in this post we will show how to send email using SMTP in laravel, email is very basic and most important feature in web development field and it is necessary for all client.

So, in this tutorial I will give you information about send mail in laravel. So, follow below steps.

Send Email In Laravel

https://websolutionstuff.com/post/send-email-in-laravel

#laravel #php #send email in laravel #email #how to send email in laravel #laravel send mail

I am Developer

1613800156

Laravel 8 Send SMS to Mobile with Nexmo Tutorial

Laravel 8 send sms using nexmo example. In this tutorial, you will learn how to integrate sms gateway and send sms notification to mobile using nexmo in laravel 8 app.

This tutorial will guide you step by step on how to send send sms to mobile with nexmo in laravel 8 app. Now, You need to follow the some step to done laravel nexmo message.

First of all, visit the following link https://dashboard.nexmo.com/sign-in and create nexmo account. Get client id and secret from nexom account.

https://www.tutsmake.com/laravel-8-send-sms-to-mobile-with-nexmo-example/

#send sms with nexmo on laravel #nexmo message send sms #laravel send sms notification #nexmo sms installation laravel #how to integrate sms gateway in laravel