R
R
Rodion Yurchenko2017-10-13 12:03:57
Laravel
Rodion Yurchenko, 2017-10-13 12:03:57

Is it good to use dynamic model properties in the view?

Good afternoon!
Started learning laravel. And immediately I want to learn as close as possible to the "correct variant".
The task is simple, there is a user and his articles The
question is in the title itself ...
If it is more detailed, then I don’t know which of the options is more correct (they both work)
option 1:
In the controller, get all the necessary data to display: The user, his articles

// почти псевдокод, но думаю суть понятна
$user = User:find(2);
$articles = $user->articles()
return функция_отображения

and in the template already use these 2 variables
OR
get only the user in the controller and pass it to view
A already in view get his articles {{ $user->articles }}
Both options work, but something tells me that the 1st option is "more correct "than the 2nd
All the same, getting the user's articles in the view is like working with the database, and this doesn’t seem to be good
Point me in the right direction so that later I don’t have to blush in front of senior employees for my code
Well, if somewhere there are examples of "correct spelling code" by Lara, I will be very grateful for the links

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mokhirjon Naimov, 2017-10-13
@zvermafia

The first option is better. But if $articlesyou just need to enter it on the screen, then I think it's even better like this:

// controller
$user = User::with('articles')->findOrFail($id);

// view
$user->articles // Без скобок! Данные уже были загружены и еще одного запроса к БД не будет

Details here: Eager Loading .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question