R
R
Roman2019-02-24 22:46:37
Laravel
Roman, 2019-02-24 22:46:37

How to properly optimize running code (here, the code is small) in Laravel?

Hello.
In my Profile project, this is a model separate from the User. And it actively interacts with other entities (in fact, the User is just for authentication and authorization, and everything else is on the Profile).
At this stage, I write the following code in the controllers:

private function getProfile()
{
    $auth_id = Auth::id(); //id текущего пользователя
    $user = User::find($auth_id); //получаем объект текущего пользователя

    $profile = Profile::firstOrNew(['user_id' => $auth_id]); //ищем или создаем кастомера для текущего пользователя
    $user->profiles()->save($profile); // сохраняем его в базе вместе с отношением к текущему юзеру

    return $profile;
}

Right in every controller where the Profile entity is used.
And then I already use the $profile object. And it works.
Yes, I understand that this is tin-tin)) but that's why I started this topic.
What is the best way to deal with such a situation?
Just don't write general phrases like "you need to use a service layer" or something like that. I already understand that something needs to be used here, which I don’t quite understand yet))
In general, the more specific, the better.
Thank you.
PS And yes, I also understand that there are several options. What is the softest for a beginner? I think it can just be stuffed into the model somehow so that at least in each controller this code is not duplicated. In fact, of course, it is necessary that a Profile be created during registration, but then you still have to check whether it exists or not, so this is not important at this stage. It's just that I'm afraid to dig deep into all these "listeners" and "containers"))) It's better to do it in such a way that you understand what you're doing...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2019-02-26
@procode

I just transferred the code from the controller to the Profile model and made the method static
. I call the Profile::getCurrent() type in the controller.
It works))
But I understand that this does not even belong in the model. At least not in this form.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question