Laravel 9 Upload CSV File Example Without Packages

Hello Artisan,

In this Laravel 9 import CSV file example tutorial, I will show you the import CSV file to the database in laravel example without packages. We can upload CSV files in Laravel into a database using packages very easily. But in this example, I will show you the way of uploading CSV files in Laravel without packages.

I will use the str_getcsv function to parse our CSV file into an array then we will save it into the database after completing validation before saving. We can use maatwebsite/excel composer package but in this example, we won't use this package. 

So let's start our CSV upload tutorial in Laravel without any packages. You have to just follow a few steps to complete this upload a CSV file in Laravel 9 applications.

 

Step 1: Download Laravel 9

This step is not necessary; So, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

 

Step 2: Create Routes

In this step, we need to create routes for a list of users, import users. so open your "routes/web.php" file and add the following route.

routes/web.php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ImportController;

Route::controller(ImportController::class)->group(function () {
    Route::post('/import', 'import')->name('user.import');
});

 

Step 3: Create Controller

Now in this controller, we will write our login to upload CSV file data in Laravel applications. So update the controller like:

app/Http/Controllers/ImportController.php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class ImportController extends Controller
{  
    private $rows = [];
    
    public function import(Request $request)
    {
        $path = $request->file('file')->getRealPath();
        $records = array_map('str_getcsv', file($path));

        if (! count($records) > 0) {
           return 'Error...';
        }

        // Get field names from header column
        $fields = array_map('strtolower', $records[0]);

        // Remove the header column
        array_shift($records);

        foreach ($records as $record) {
            if (count($fields) != count($record)) {
                return 'csv_upload_invalid_data';
            }

            // Decode unwanted html entities
            $record =  array_map("html_entity_decode", $record);

            // Set the field name as key
            $record = array_combine($fields, $record);

            // Get the clean data
            $this->rows[] = $this->clear_encoding_str($record);
        }

        foreach ($this->rows as $data) {
            User::create([
               'name' => $data['name'],
               'email' => $data['email'],
               'password' => bcrypt($data['password'])
            ]);
        }

        return to_route('user.create');
    }
    
    private function clear_encoding_str($value)
    {
        if (is_array($value)) {
            $clean = [];
            foreach ($value as $key => $val) {
                $clean[$key] = mb_convert_encoding($val, 'UTF-8', 'UTF-8');
            }
            return $clean;
        }
        return mb_convert_encoding($value, 'UTF-8', 'UTF-8');
    }

}

 

Step 4: Create Blade File

In the last step, let's create welcome.blade.php(resources/views/welcome.blade.php) for layout and we will write design code here and put the following code: Here we will create our CSV import form to upload it into the database.

resources/views/welcome.blade.php

 

Read also: Upload Large CSV File using Queue Job Batching in Laravel

 

Hope this Laravel 9 CSV file upload tutorial will help you.

 

#laravel #laravel-9x