E
E
Edgr2020-12-31 19:24:12
Laravel
Edgr, 2020-12-31 19:24:12

Laravel. How to competently implement the registration of several types of users with completely different fields?

Hi everybody!
I work on the "job search" portal, something similar to hh.ru. At the moment, I have implemented registration / authorization using polymorphic links, I will give a small example:
- the User entity (User) stores only email and password fields, has a link

public function profile()
    {
        return $this->morphTo();
    }
this is convenient because when authorizing, it is enough to have one entry point and the system will return the user regardless of his type;
- added two entities Jobseeker and Employer, have a relationship
public function user()
    {
        return $this->morphOne('App\User', 'profile');
    }

At first, this approach seemed acceptable to me, but the farther into the "forest", the more complex ...
When I try to get the user, I have to call as follows
Auth::user()->profile
// Проверять пользователя 
Auth::user()->profile->isEmployer()
// Компания может обновить менеджера (рекрутера), 
// для этого в сущность Employer метод update() ломаю голову что лучше передавать id User и доставать снова 
$user = User::findOrFail($id); 
$user->profile()->update(...) 
//или id Employer и 
$employer->findOrFail($id); 
$employer->update(...)

//  и самое больное место это создание и обновление пользователя,
// для меня этот кусок кода смотрится ужасно 
// побочный эффект полиморфных связей
$employer = Employer::create([
   'phone' => $request->get('phone'),
   'full_name' => $request->get('full_name'),
    'company_id' => Auth::user()->profile->company_id
 ]);

$employer->user()->create([
   'email' => $request->get('email'),
   'password' => $request->get('password')
]);

Next, I found another implementation, by adding a new guard in the auth config, but with this approach, I seem to have to duplicate the authorization, registration, etc. controllers.
I would appreciate some good advice, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuri Kulaxyz, 2020-12-31
@Kulaxyz

It can be implemented through roles for example .
By combining all the fields into one table, specifying AND in the code, it is easy to check through Gate. nullable()->default(null)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question