Use like this Verify::dispatch($user);
Passing locale to all queued Mails?
When I queue a Mail like:
dispatch(new Verify($user));
I forgot to add the language of the session.
Now, I could request the session's language in front of every dispatch and pass $language to the queue:
if ($request->session()->has('lang') && $request->session()->get('lang') === 'en') {
$language = 'en';
} elseif ($request->session()->has('lang') && $request->session()->get('lang') === 'es') {
$language = 'es';
} else {
$language = 'en';
}
dispatch(new Verify($user, $language));
and then reference it within the Jobs:
Mail::to($this->user->email)->locale($language)->send($email);
That would be no problem, but a bit repetitive. Is there a path, where I would not have to add $language to every dispatch in every Controller?
@splendidkeen you need to check your logic for when changing languages, whether it changes the language for the session or not. If you have a middleware you need to include it on the routes or it depends on how you are handling the language change because this solution works just fine for setting the locale or language for the jobs or mails...
so basically it would be somthing like this. LanguageSwitcher Middleware
namespace App\Http\Middleware;
use Closure;
use Carbon\Carbon;
class LanguageSwitcher
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(session()->has('locale')){
app()->setLocale(session()->get('locale'));
Carbon::setLocale(session()->get('locale'));
}
return $next($request);
}
}
Register in the app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\LanguageSwitcher::class,
...
];
LanguageSwitcherController.php
class LanguageSwitcherController extends Controller
{
public function switch($locale){
session()->put('locale', $locale);
session()->save();
return back();
}
}
Route
Route::get('locale/{locale}', 'LanguageSwitcherController@switch');
blade/html snippet - you can change it based on your design...
<div class="btn-group btn-collection btn-icon-group mr-3">
<a class="btn btn-secondary" href="/locale/en">EN</a>
<a class="btn btn-secondary" href="/locale/es">ES</a>
</div>
if you have this setup for changing the language this trait for the jobs would work just fine.
Please or to participate in this conversation.