How to dynamically convert the attribute?

Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
There is a database in which such a structure:
id | title_en | title_ru | ...
That is, the choice of language must take on a particular title

Have done so:
$items = Item::all(); foreach ($items as $item) { $item->makeVisible('title_' . $request->lang); // lang is taken from the parameter, or headers, or "en" }

It turned out as it should, but encountered a problem on that front now too, should correct it to handle because the attribute itself has the _ru, _en ...

And I would like to when front comes to language, the attribute would be only one title, without any title_ru, title_en, etc.

Whether it is possible to arrange it?
Thought of as the model to do it, but you cannot refer to a request?

So that's changed too much:
$items = Item::all(); foreach ($items as $item) { $title = 'title_' . $request->lang; $item->title = $item->$title; }

But maybe there's still a better solution?
by | 15 views

1 Answer

0 like 0 dislike
The selected language must not be installed in the controller.

That is, you need somewhere else to the controller, for example in the service provider to obtain the language from the request or from session/database/configs and keep it available for collection at any point.

Then implement a method of the model, in the form of a mutator, to retrieve the value the required fields on the basis of the previously installed language variable.

Related questions

0 like 0 dislike
2 answers
asked May 12, 2019 by troodi
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
110,608 questions
257,187 answers
40,796 users