vluzrmos / laravel-language-detector

Detect the language for your application using browser preferences, subdomains or route prefixes.
109 stars 25 forks source link

Doesn't work in Jobs. Default language is loaded in jobs #34

Closed pa-ra-kram closed 3 years ago

pa-ra-kram commented 4 years ago

Laravel loads default language in job queues. It is probably because the queues are processed independently of the app language.

I was trying to send emails via queues, and it was always sending emails in English, regardless of the user's language.

To handle this, the language needs to be explicitly passed to the job.

Solution:

//Creating payload and sending it to the job
$payload = array(
        'email' => $email,
        .........
        .........
        'language' => \App::getLocale() //Passing current locale along with other payload data
);
      //send email
      $job = new MyEmailOrAnyOtherJob($payload);

In the job file

Receive the payload array as usual, and set the locale manually.

class MyEmailOrAnyOtherJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
      $payload = $this->payload;
      \App::setLocale($payload['language']);
        .........
        //Rest of the code
        .........
     }
vluzrmos commented 4 years ago

Hi @pa-ra-krum !

This package is bound to the current request, so in a scheduled/queued job it will have no effect. You should do your own business logic to acomplish that, like:

1 - Pass the current locale to the Job 2 - Save the current locale on users table when he enters on the website