Laravel eloquent multiple dependent model

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 va…


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;
    }
}

Image description

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);

Image description

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');
    }

Image description

$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'
        );
    }

Image description

In User Model file User.php

public function employee(){
        return $this->hasMany(Employee::class);
    }

Image description

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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Laravel eloquent multiple dependent model." vamsikrishna71 | Sciencx - Sunday July 10, 2022, https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/
HARVARD
vamsikrishna71 | Sciencx Sunday July 10, 2022 » Laravel eloquent multiple dependent model., viewed ,<https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/>
VANCOUVER
vamsikrishna71 | Sciencx - » Laravel eloquent multiple dependent model. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/
CHICAGO
" » Laravel eloquent multiple dependent model." vamsikrishna71 | Sciencx - Accessed . https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/
IEEE
" » Laravel eloquent multiple dependent model." vamsikrishna71 | Sciencx [Online]. Available: https://www.scien.cx/2022/07/10/laravel-eloquent-multiple-dependent-model/. [Accessed: ]
rf:citation
» Laravel eloquent multiple dependent model | vamsikrishna71 | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.