V
V
Vladimir Ryzhov2019-03-07 02:17:57
Laravel
Vladimir Ryzhov, 2019-03-07 02:17:57

How to make a global model in Laravel?

Records from a certain table are displayed on each page, and it turns out that in each controller in each action the same line is indicated: How can this be written so that it is global or something? I'm just starting in Laravel, not necessarily ready-made code, tell me at least which topic to watch.
$lists = List::all();

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2019-03-07
@AprelVovanya

Here is the answer to your question (based on another answer):
https://si-dev.com/blog/laravel-view-composers
Exhaustive and without water :)
// I was curious to know this myself ))

V
vism, 2019-03-07
@vism

view composer

J
jazzus, 2019-03-07
@jazzus

inside the controller you can

public $lists;

public function __construct()
{
   $this->lists = List::all();
}

and refer to methods
or method
public function getLists()
{
   return List::all();
}

and refer to methods . For the entire application, you can connect the Trait. But for such a short code, I would not bother. Only if the query is more complicated or involves refactoring in the future (in this case, exactly in a trait or model)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question