This article introduces how to insert data into multiple tables with a parent-child (one-to-many) relationship in Laravel at the same time. (Laravel version 6 series)
When registering data in the (Parent) Department: departments table, obtain the parent table’s ID, and use that ID with a for loop and save() to insert data into the (Child) Employees: employees table.
Two Table Structures with One-to-Many Relationship
We have prepared two tables with a one-to-many relationship. This structure allows registering multiple employees (employees table) belonging to a department (departments table).
Department Table: departments table (Parent)
| Name | Description |
|---|---|
| id | Primary Key |
| department_name | Department Name |
Employee Table: employees table (Child)
| Name | Description |
|---|---|
| id | Primary Key |
| employee_name | Employee Name |
| department_id | Department ID = id of departments table *The name should be “department_id”, which combines the singular form of the parent table name “department” (without “s”) and its primary key “id” with an underscore. This allows retrieving data where the ids match from the departments table. |
Prepare Models for Parent and Child Table Data
*Prepare Department model and Employee model.
Model Definition for departments Table (Parent)
*Prepare Department.php file.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
}
Model Definition for employees Table (Child)
*Prepare Employee.php file.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
}
Registration Form (Registration Page) for Department and Employees
*Prepare departmentsregister.blade.php file. This form allows registering up to 5 employees per department.
@if (session('message'))
<div class="message">
{{ session('message') }}
</div>
@endif
@include('common.errors')
<form enctype="multipart/form-data" action="{{ url('departmentsentry') }}" method="POST">
@csrf
<div>
<label for="department_name">Department Name*</label>
<input type="text" id="department_name" name="department_name" value="{{ old('department_name') }}">
</div>
<ul>
<li>
<label for="employee_name[0]">Employee Name 1</label>
<input type="text" id="employee_name[0]" name="employee_name[0]" value="{{ old('employee_name[0]') }}">
</li>
<li>
<label for="employee_name
">Employee Name 2</label>
<input type="text" id="employee_name
" name="employee_name
" value="{{ old('employee_name
') }}">
</li>
<li>
<label for="employee_name
">Employee Name 3</label>
<input type="text" id="employee_name
" name="employee_name
" value="{{ old('employee_name
') }}">
</li>
<li>
<label for="employee_name
">Employee Name 4</label>
<input type="text" id="employee_name
" name="employee_name
" value="{{ old('employee_name
') }}">
</li>
<li>
<label for="employee_name
">Employee Name 5</label>
<input type="text" id="employee_name
" name="employee_name
" value="{{ old('employee_name
') }}">
</li>
</ul>
<button type="submit" class="btn-entry">Register</button>
</form>
Route Definition
*Change the page URL as needed.
// Registration page
Route::get('/departmentsregister','DepartmentsController@register');
// Registration process
Route::post('/departmentsentry','DepartmentsController@entry');
Controller for Inserting Data into Multiple Related Tables (One-to-Many) Simultaneously
*Prepare DepartmentsController.php. When inserting data into the (Parent) Department: departments table, retrieve the parent table’s ID, and use it with a for loop and save() to insert data into the (Child) Employees: employees table.
Import Department and Employee Models
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Department; // Use Department model
use App\Employee; // Use Employee model
use Validator; // Use validation
use DB;
Registration Page and Process
*This includes the registration page display “register(Request $request)~” and registration process “entry(Request $request)~”.
In the process, after input, perform “//Validation Check”, then “//Insert into Department Table: departments table (Parent)”, then “//Get the ID inserted into departments table (Parent)”, after that “//Get Employee Names 1–5 as an array”, and within a for loop “//Insert into Employees Table: employees table (Child)” only if “//Employee name is entered”.
class DepartmentsController extends Controller{
// Registration page
public function register(Request $request)
{
return view('departmentsregister', [
]);
}
// Registration process
public function entry(Request $request) {
// Validation check
$validator = Validator::make($request->all(), [
'department_name' => 'required',
'department_name' => 'max:255',
]);
// Validation error
if ($validator->fails()) {
return redirect('/departmentsregister')
->withInput()
->withErrors($validator);
}
// Insert into Department Table: departments table (Parent)
$departments = new Department;
$departments->department_name = $request->department_name;
$departments->save();
// Get the ID inserted into departments table (Parent)
$department_id = $departments->id;
// Get Employee Names 1–5 as an array
$employee_names = $request->get('employee_name');
// Insert into Employees Table: employees table (Child)
for($i=0; $i<5; $i++){
// Only insert if employee name is entered
if($employee_names[$i] != "" && !empty($employee_names[$i])){
$employee = New Employee;
$employee->department_id = $department_id; // Insert ID from departments table (Parent)
$employee->employee_names = $employee_names[$i];
$employee->save();
}
}
return redirect('/departmentsregister')->with('message', 'Data has been registered.');
}
}
*Please use at your own risk if you reuse this code.