I have a mutator that converts the model's body in desired translated format.
public function getTextAttribute() {
return $this->constructText($this->body); // which does __($key, $value)
}
protected $appends = ['text'];
However, once they are in the queued job, I can't change locale whatever I tried and even I pass an Eloquent Collection, it changes them to default locale too.
What I tried:
Before firing the job, passing $locale and $eloquentCollection to the job.
MyEvent::dispatch($collection, $language)
And in my job,
public function __construct($collection, $language)
{
app()->setLocale($language);
// if I log here, it logs the given locale as my current locale
// but as soon as hits the get mutator, it goes back to default locale
}
In my collection, I tried putting a property:
class MyModel extends Model { public $locale = null; }
And in my job,
public function __construct($collection, $language)
{
app()->setLocale($language);
$collection->each(function($item) {
$item->locale = $language;
})
}
And changed the mutator to:
public function getTextAttribute() {
if (!$this->locale) {
$this->locale = app()->getLocale();
}
return $this->constructText($this->body, $this->locale);
// which does __($key, $value, $locale) inside
}
However this didn't work either. When I log inside constructText()
the $locale - it returns the default locale too.
Is there any way or workaround you can think of? 2 other possible workarounds came to my mind are:
Is there a way to prevent Eloquent models in collection to get mutated?
Is there a way to convert eloquent collection values (including 'text') to an object (without having connection to the actual models)? so I can give it directly to the job.