A
A
Artem00712018-05-04 15:40:49
Laravel
Artem0071, 2018-05-04 15:40:49

How to dynamically convert an attribute?

There is a database in which such a structure:
id | title_en | title_ru | ...
That is, one or another header should be taken from the choice of language.
I did this:

$items = Item::all();
foreach ($items as $item) {
    $item->makeVisible('title_' . $request->lang); // lang беру из параметра, или header'а, или "en"
}

It turned out as it should, but I ran into the problem that now it is also necessary to process everything correctly on the front, because the attribute itself has either _ru or _en ...
And I would like that when the language comes from the front, the attribute would be only one "title" , without any title_ru, title_en, etc.
Is it possible to arrange this somehow?
I thought to do it somehow in the model, but you can’t turn to request there, right?
==============================
This is how I changed the enumeration:
$items = Item::all();
foreach ($items as $item) {
    $title = 'title_' . $request->lang;
    $item->title = $item->$title;
}

But maybe there is a better solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yan-s, 2018-05-04
@Yan-s

The selected language must not be set in the controller.
That is, you need somewhere else before the controller, for example, in the service provider, get the language from request or from the session / database / configs and keep it available for receiving at any point.
Then implement the model method, it is possible in the form of a mutator, to get the value of the desired field based on the previously set language variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question