This content originally appeared on DEV Community and was authored by vamsikrishna71
Laravel eloquent multiple dependent model
How to Implement the Import CSV with Validation of Null Values?
Lets Start
What is CSV ?
CSV or Comma-Separated Values are text files delimited by using commas to separate values, but sometimes also using other characters such as semicolons. Each record consists of one or more fields separated by commas. The use of commas as separators (fields) is the source of the name for this file format. CSV files usually store tabular data (numbers and text) in plain text, in which case each row will have the same number of fields.
How to Import CSV in Laravel 9?
In laravel 9, to make a feature to import data from files in CSV format to a database or export data in CSV format, we can use the laravel-excel package. The ways of implementation will be discussed below.
Import in Laravel 9
Import CSV
Step 1: Install Laravel
Step 2: Setup Database
Step 3: Create Models
Import CSV
Ok, the first feature we created is a feature to import data from a CSV format file to the users table in the database.
CSV to Array trait
Create Traits folder inside the App directory
namespace App\Traits;
trait CsvToArray
{
/**
* Converts the CSV DATA to an Array with uploaded files
*
* @param string $filename
* @param string $delimiter
* @return array
*/
public function csvToArray(string $filename = '', string $delimiter = ',')
{
if (!file_exists($filename) || !is_readable($filename)) {
return false;
}
$header = null;
$data = [];
if (($handle = fopen($filename, 'r')) !== false) {
while (($row = fgetcsv(
$handle,
1000,
$delimiter
)) !== false) {
if (!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
}
Multiple Dependent Model
Which is Dependent with one on another data, which distribute along the Primary key of the parent table and foreign key on the child table.
public function importEmployee(Request $request)
{
$request->validate(
[
'file' => ['required', 'mimes:csv,txt'],
]
);
$fileName = time() . '.' . $request->file->getClientOriginalExtension();
$request->file->move(public_path('uploads'), $fileName);
$csvFile = public_path('uploads/' . $fileName);
$employees = $this->csvToArray($csvFile);
$user = User::find(Auth::user()->id);
In File upload input make field as accept = csv only.
Here, Dependent model Employee has the data from user to create the new employees.
foreach ($employees as $employee) {
$user->employee()->create([
'username' => ' ' ? $employee['email'] : $employee['username'],
'employeeId' => $employee['employeeId'],
'first_name' => $employee['first_name'],
'last_name' => $employee['last_name'],
'email' => $employee['email'],
'department' => $employee['department'],
'designation' => $employee['designation'],
'password' => ' ' ? Hash::make($employee['email']) : Hash::make($employee['password']),
]);
}
return redirect('employee.details')
->with('success', 'Employee updated Successfully');
}
$user = User::find(Auth::user()->id);
$user->employee()->create
Above Two lines which are most important to understand.
In Employee Model file Employee.php
public function user()
{
return $this->belongsTo(
User::class,
'user_id',
'id'
);
}
In User Model file User.php
public function employee(){
return $this->hasMany(Employee::class);
}
Route file web.php
Route::post('importEmployee', [App\Http\Controllers\EmployeeImportController::class, 'importEmployee']);
Conclusion
In this article, we have both learned how to create an import data with related of multiple model in Eloquent ORM in CSV format in laravel 9.
This content originally appeared on DEV Community and was authored by vamsikrishna71
vamsikrishna71 | Sciencx (2022-07-10T11:45:44+00:00) Laravel eloquent multiple dependent model. Retrieved from https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.