Laravel Import or insert CSV file into database | Import CSV file to Laravel controller and insert data to tables | How to import CSV in Laravel

To import a CSV file into a Laravel application, you can follow these steps to create a feature that reads a CSV file and inserts its data into a database table.

  1. Create a Database Table:

    Make sure you have a database table to store the CSV data. You can create a migration for the table using the Artisan command:

    bash
php artisan make:migration create_csv_data_table

Edit the migration file (created in the database/migrations directory) to define the table's structure. Then, run the migration to create the table:

bash
  • php artisan migrate
  • Create a Route and Controller:

    Create a route in the routes/web.php file that points to a controller method responsible for handling CSV imports:

    php
  • Route::get('/import-csv', 'CsvImportController@index'); Route::post('/import-csv', 'CsvImportController@store');

    Next, generate a controller called CsvImportController:

    bash
  • php artisan make:controller CsvImportController

    In the CsvImportController, you will implement the methods to handle the CSV import process.

  • Create a Form for Uploading CSV:

    In your Blade view file, create a form that allows users to upload a CSV file. Typically, this form would be associated with the store route you defined earlier:

    html
  • <form action="/import-csv" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="csv_file" accept=".csv"> <button type="submit">Upload CSV</button> </form>
  • Implement the CSV Import Logic:

    In the CsvImportController, implement the logic to read and insert data from the uploaded CSV file into the database. Here's a simplified example:

    php
    1. // CsvImportController.php use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; class CsvImportController extends Controller { public function index() { return view('import-csv'); } public function store(Request $request) { $request->validate([ 'csv_file' => 'required|file|mimes:csv,txt', ]); $file = $request->file('csv_file'); $path = $file->store('temp'); // Store the uploaded file temporarily // Process and insert CSV data into the database $csvData = array_map('str_getcsv', file(storage_path('app/' . $path))); $headers = array_shift($csvData); foreach ($csvData as $row) { $data = array_combine($headers, $row); // Insert data into the database table DB::table('your_table_name')->insert($data); } // Delete the temporary CSV file Storage::delete($path); return redirect('/import-csv')->with('success', 'CSV file imported successfully'); } }

      In this example, the store method processes the uploaded CSV file, reads its content, and inserts it into the database table. Make sure to replace 'your_table_name' with the name of your actual database table.

    2. Handle Validation and Display Errors:

      You can add validation and error handling to ensure the uploaded file is a valid CSV file and handle any potential errors during the import process.

    3. Display Success Message:

      After a successful import, you can redirect the user back to the import form and display a success message to confirm that the CSV file was imported successfully.

    With these steps, you can create a feature in your Laravel application to import CSV files and insert their data into a database table.

    Comments