How to Read CSV File In Laravel 10

How to Read CSV File In Laravel 10

Reading a CSV file in Laravel 10 can be done using the built-in functions provided by PHP. In this article, we will show you how to read a CSV file in Laravel 10 step by step.

Step 1: Create a Route First, create a route in the web.php file. This route will point to a controller method that will read the CSV file.

In this example, we’re creating a route with the URL /read-csv, and the second parameter is the name of the controller method that will handle the request, which is readCsv() in the CsvController.

Make sure to replace CsvController with the actual name of your controller, and to make sure that the namespace is correct.

Route::get('/read-csv', 'CsvController@readCsv');

Step 2: Create a Controller Create a new controller named CsvController using the following command:

The command php artisan make:controller CsvController creates a new controller file in Laravel.

Here’s a rundown of what this command does:

php artisan: This command is used to interact with Laravel’s command-line interface.
create:controller: This is the command that creates a new controller file.
CsvController: This is the name of the controller file to be created.
After running this command, Laravel will generate a new file named CsvController.php in the app/Http/Controllers directory of your Laravel project. This controller file will be used to handle the logic of reading the CSV file.

php artisan make:controller CsvController

Then, add the following method to read the CSV file in the CsvController:

public function readCsv()
    $csvFile = public_path('data.csv');
    $csv = array_map('str_getcsv', file($csvFile));

    return view('', ['csv' => $csv]);

This is a PHP function that reads data from a CSV file and returns it as a view. Let’s break it down:

  • The first line defines the function and its name is “readCsv”. This function doesn’t take any parameters.
  • The second line sets the variable $csvFile to the path of the CSV file. The “public_path” function returns the absolute path to the “public” directory of the application.
  • The third line reads the contents of the CSV file using the “file” function, which returns an array of lines. The “array_map” function is then used to apply the “str_getcsv” function to each line, which parses the CSV line into an array of values. The resulting array is stored in the $csv variable.
  • Finally, the function returns a view called “”, passing the $csv variable as a parameter.

Note that this code assumes that the CSV file exists and is readable by the PHP process. Additionally, this code doesn’t perform any validation or filtering on the data read from the CSV file, so it’s important to be careful when using this function with untrusted input.

The code above reads the data.csv file in the public folder and returns a view with the CSV data.

Step 3: Create a View Create a new view named read.blade.php in the resources/views/csv folder with the following code:

        @foreach($csv as $row)
                <td>{{ $row[0] }}</td>
                <td>{{ $row[1] }}</td>

This is a HTML table that displays the contents of the CSV file that was passed to the view. Let’s break it down:

  • The table starts with the <table> tag, which defines a table.
  • The <thead> tag defines the table header row, which contains two columns: “Name” and “Email”.
  • The <tbody> tag defines the table body, which will contain the data rows.
  • The “@foreach” directive is a control structure in Blade, a PHP templating engine commonly used in Laravel. It loops through each row in the $csv array and creates a new table row for each one.
  • The <tr> tag defines a table row.
  • The <td> tag defines a table cell.
  • The “{{ }}” syntax is used to output the values of the Name and Email fields in each row of the CSV file. The values are accessed using the array index notation, where $row[0] corresponds to the first column in the CSV file (Name) and $row[1] corresponds to the second column (Email).
  • Finally, the </tr> and </table> tags close the table row and table, respectively.

This HTML code will generate a table with two columns (Name and Email) and one row for each record in the CSV file.

This code creates a table with the CSV data.

Step 4: Add CSV Data Add some data to the data.csv file in the public folder:

Based on the HTML code provided, the CSV file should be structured as follows:

  • The first line should contain the column headers “Name” and “Email”, separated by a comma.
  • Each subsequent line should contain a record, with the Name and Email fields separated by a comma.
John Doe,[email protected]
Jane Doe,[email protected]

When the “readCsv” function is called and passed this CSV file as an argument, the HTML table will be generated with two rows, one for each record in the CSV file, displaying the name and email address of each person.

Step 5: Test the Code Visit the URL http://localhost/read-csv in your web browser to test the code. You should see a table with the CSV data.

You can test the code by following these steps:

  1. Make sure you have a web server installed on your local machine, such as Apache or Nginx, and that it is running.
  2. Place the PHP file containing the readCsv function and the Blade template file in a folder that is accessible to your web server.
  3. Make sure the CSV file is located in the same folder as the PHP and Blade files.
  4. In a web browser, visit the URL http://localhost/read-csv, where “localhost” is the hostname or IP address of your local machine.
  5. If everything is set up correctly, you should see a table with the data from the CSV file displayed in your web browser.

If you encounter any errors or unexpected behavior, check the PHP error logs for more information.

To sum up, reading data from a CSV file in Laravel is an easy procedure. You should be able to easily read data from a CSV file in your Laravel application by following the instructions provided in this article.

This Article Ideas has been taken from the following websites; which are following:

Laravel 10 Read CSV File Example

Laravel 10 Import Export Excel & CSV File Example

How to import CSV in Laravel and Choose Matching Fields


Leave a Reply

Your email address will not be published. Required fields are marked *