Sometimes frontend dictates how you have to create your models on the backend. So if that is how business owners decided to do it, then there is no way around it. You have to do it in one request.
Laravel/Lumen 7+ best practice to store One To Many relationship
Hello,
I'm pretty new to Laravel ecosystem and want to develop with best practice as much as possible. What is the best way to store One To many relationship using Eloquent?
Here is my case: I have "staffs" members table, with a One To Many relationship with a "staffDependants" table, so a staff member can have multiple staff dependants. When I create a staff entity and to avoid doing multiple http request, my front-end is sending a pakcage with the new staff member and its staffDependants entities to create with it. My payload is like this :
{
staff: {// staffData...}
staffDependants: [
{// staffDependantData...},
{// staffDependantData...},
{// staffDependantData...},
{// staffDependantData...}
]
}
This is my current setup to save the staff, than its staff dependants. It works, but is it the right "Laravelish" way ?
This is my create function in the StaffController :
public function create(Request $request)
{
try {
DB::transaction(function () use ($request) {
// Staff
$this->validateCreateStaff($request);
$staff = new Staff;
$staff->last_name = $request->input('staff.firstName');
$staff->first_name = $request->input('staff.lastName');
//...
$staff->partner_nationality_alpha2 = $request->input('staff.partnerNationality');
$staff->partner_is_handicapped = $request->input('staff.partnerIsHandicapped') ? 1 : 0;
$staff->partner_is_dependant = $request->input('staff.partnerIsDependant') ? 1 : 0;
// StaffDependants
$this->validateCreateStaffDependants($request);
$staffDependants = [];
foreach ($request->input('staffDependants') as $staffDependant) {
$tmpStaffDependant = new StaffDependant;
$tmpStaffDependant->last_name = $staffDependant["lastName"];
$tmpStaffDependant->first_name = $staffDependant["firstName"];
$tmpStaffDependant->birth_date = $staffDependant["birthDate"];
$tmpStaffDependant->staff_dependant_type_id = $staffDependant["staffDependantType"];
$tmpStaffDependant->is_handicapped = $staffDependant["isHandicapped"];
$tmpStaffDependant->end_date = $staffDependant["endDate"];
array_push($staffDependants, $tmpStaffDependant);
}
$staff->save();
$staff->staffDependants()->saveMany($staffDependants);
return response()->json([
'staff' => $staff,
'staffDependants' => $staffDependants,
'message' => 'CREATED'
], 201);
});
} catch (\Exception $e) {
return response()->json(['message' => $e], 409);
}
}
Is there even a less verbose way to achieve this kind of thing?
Please or to participate in this conversation.