Home > Blockchain >  Send Laravel notifications according to custom user locale value
Send Laravel notifications according to custom user locale value

Time:11-24

I'm looking for the best approach to build notifications in Laravel based on users locale value (english and spanish).

SomeController.php (that sends the notification):

Notification::send(User::find($some_id), new CustomNotification($some_parameter));

CustomNotification.php:

class CustomNotification extends Notification
{
    use Queueable;
    protected $title, $body, $foot;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($some_parameter)
    {
        $this->title = __('Some Title');
        $this->response = __('Some Response');
        $this->foot = 'My WebPage Title';
    }
    ...
}

With the CustomNotification construct the values of $title and $response will be translated according to the current user who send the notification, but in this case the admin is the one who sends it, so the values of this variables will be in the admin locale and not the user.

CodePudding user response:

well in this case you should store locale in the users table, then you can send it (or at least his locale) to the notification constructor:

$user=User::find($some_id);

Notification::send($user, new CustomNotification($some_parameter,$user));

and in your notification class:

class CustomNotification extends Notification
{
    use Queueable;
    protected $title, $body, $foot;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($some_parameter,User $user)
    {
       
        App::setLocale($user->locale??$defaultLocale);

        $this->title = __('Some Title');
        $this->response = __('Some Response');
        $this->foot = 'My WebPage Title';
    }
    ...
}
  • Related