Search code examples
phplaravelwamplaravel-mail

Send notification to email


I work on a website project with the laravel framework and I want when I click on the button send a notification either send to the user's email

  $invite = Invite::create([
    'name' => $request->get('name'),
    'email' => $request->get('email'),
    'token' => str_random(60),
]);

$invite->notify(new UserInvite());

tnx to help me


Solution

  • What you are using is mail notification, Here is the answer but you can refer to notification section of laravel docs for more information:

    https://laravel.com/docs/5.4/notifications

    first generate the notification using your terminal in project folder:

    php artisan make:notification UserInvite

    Then in generated file specify your driver to be 'Mail'. byr default it is. Also laravel has a nice sample code there. And it is better you inject your $invite to the notification so you can use it there. here is a quick sample code. You can find the notification generated under App\Notifications.

    <?php
    
    namespace App\Notifications;
    
    use Illuminate\Bus\Queueable;
    use Illuminate\Notifications\Notification;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Notifications\Messages\MailMessage;
    use App\Invite;
    
    class UserInvite extends Notification implements ShouldQueue
    {
    use Queueable;
    
    
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    
    public function via($notifiable)
    {
        return ['mail']; // Here you specify your driver, your case is Mail
    }
    
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->greeting('Your greeting comes here')
            ->line('The introduction to the notification.') //here is your lines in email
            ->action('Notification Action', url('/')) // here is your button
            ->line("You can use {$notifiable->token}"); // another line and you can add many lines
    }
    }
    

    now you can call your notification:

    $invite->notify(new UserInvite());
    

    since you are notifying on invite, your notifiable is the same invite. As a result in your notification you can use $notification->token to retrieve the token of invite object.

    Please let me know if I can be of any help. regards.