R
R
Roquie2015-02-13 14:02:07
Laravel
Roquie, 2015-02-13 14:02:07

Using the user ID in models. Is it correct?

Essence: In each model, 5 - 10 methods, which need `$user_id` like air. Calling each in the controller, you must always pass the user ID - just some kind of torment, I don’t know chtoli :).
Is it correct to set the property in the base model:

public function __construct()
{
     $this->user = \Auth::getUser();
}

...and then use it as needed in the rest.
Or can it then turn into "dire consequences"?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey, 2015-02-13
@rdifb0

As for me, it’s quite correct, it’s another matter what is better for hardcoding, but passing it as a parameter to the constructor.

S
Sergey Gladkovskiy, 2015-02-13
@SMGladkovskiy

The presence (and their further increase) of 5-10 methods in the model can turn into deplorable consequences. :) Use the "repository" pattern or CQRS.
If everything is fine, then the presence of a userId definition in the model is normal.

M
Maxim Kudryavtsev, 2015-02-13
@kumaxim

For starters, 5-10 methods in the model ... What kind of model do you have there?
About the id_user field: if your logic implies that only 1 user will work with one instance of the model, declare an additional field and initialize it in the constructor.
By the way, as one of the options, if you need to be sure that this very id_user will not change for some reason during the execution of the model method and will not pull everything with it in a snowball, use it as the default parameter
In the method itself, work not with $this->_id_user, which is initialized in your controller, but with $id_user, which is a parameter of this particular method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question