Answer the question
In order to leave comments, you need to log in
Creating Linked Records Laravel Eloquent?
Hello, the question arose of how to create linked records in Laravel, let's say there are 3 tables User, Role and Profile, data for these tables comes in the creation request, for example {data:{user[],role:[],profile}}, fields role and profile can be empty, there is a special service for the user with the create method, so is it right to do checks for the emptiness of these fields directly in this method and create role and profile records with binding by id to the user, how to properly separate this logic into within laravel, create separate services for role and user and then call their create methods
I would be very grateful if you provide code or pseudocode examples
Answer the question
In order to leave comments, you need to log in
What kind of connections?
Let's say the user role is many-to-many
class User {
public function roles(): BelongsToMany {
return $this->belongsToMany(Role::class);
}
}
class Role {
public function users(): BelongsToMany {
return $this->belongsToMany(User::class);
}
}
$user = User::create([...]);
$user->roles()->attach(Role::whereSlug('user')->firstOrFail());
$user->profiles()->create([
]);
There is no right answer, there is the best matched solution for each individual case)
From the point of view of separating services according to duties, it would be more correct to make a separate service for each action.
Let's say we have an infrastructure controller class (not necessarily a controller in our understanding), which all it does is outsource work to other classes and does not contain business logic.
In such a controller class, I would instruct the user service to create a user.
Pass the created user to the role service and do $user->create(attributes) from him. Just give them fillable fields in the model in advance, otherwise the attributes themselves will not fill the model.
In the same way, we create a profile.
Thus, the infrastructure class did not take over any logic and all services remained clean in terms of incoming dependencies. Validate lara in the request form.
It is not necessary to drag model services around, you can do CreateUserDto. But then we start making symphonies out of the lara.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question