How-to import CSV files in Laravel (it'll take just 5min to setup with UseCSV)

Jun 9, 2022

CSV is everywhere. It's in marketing, sales, finance, customer service, and operations. Where there is data, there is a high chance that CSV is also present in some form.

UseCSV is a tool that makes it easy to work with CSV files in Laravel, by providing an easy-to-use interface for importing and exporting data.

Some of the benefits of using UseCSV include:

  • Easy to use interface for importing and exporting data
  • Well structured data format
  • Can be easily integrated into your Laravel app

If you're a Laravel developer looking to integrate CSV importing into your app, this is where UseCSV comes in.

What is UseCSV?

UseCSV is an all-in-one CSV import product that gives you a delightful CSV importer experience for your users. All you have to do is drop-in the UseCSV JS library, and create a webhook endpoint to receive uploads. This takes away all the headaches of building CSV import functionality in-house .

Here's a sneak peak of what the import experience will be for your users (this opens in a modal inside your app):

Here are just a few of the awesome features of UseCSV:

  • Frontend libraries which add the UseCSV import button and modal to your app
  • Supports CSV and all Excel formats (xlsx, xls, xlt), including legacy Excel versions
  • Handles large import files
  • Includes a library of common validation rules to choose from

Without further ado, let's get started!

Setting up your UseCSV account

To set up your free UseCSV developer account, simply follow this link - no credit card details required - just an email address or Gmail account. Once completed, you will be automatically directed the to UseCSV dashboard.

This dashboard will give you an overview of your CSV importers, a link to the documentation, API keys, account settings, and billing. In the top right corner is the 'Add Importer' button. This button will give you the ability to create a new data model for your CSV imports.

UseCSV-admin-home

To edit a current data model, click on the View button that is on the same row as your selected importer. When you create an account, there an importer already created for you called 'My First Importer'. Click View to configure visit the importer settings:

UseCSV-admin-my-first-importer

Head down to the Column section, where you can setup the data model for this importer.

UseCSV-admin-columns.png

Click Add Column to create a new column, for example you could add a first_name column to begin with. Create as many columns as you like.

UseCSV-admin-add-column.png

Add CSV import to your JavaScript Laravel app

Laravel is a PHP framework for modern web applications. It is built on top of the Symfony PHP framework and makes use of many of its components. Laravel aims to make the development process simple and efficient by providing an elegant, simple syntax for common tasks.

In this tutorial, we will show you how to add UseCSV via JavaScript to your Laravel application and use it in the frontend.

Step 1: install Laravel JavaScript and UseCSV library

First, we will need to install the Laravel JavaScript package:

composer require laravel/javascript

Once the package has been installed, we can now add our JavaScript code to the resources/js/ directory.

You can install usecsv npm package to a specific location by using the --prefix option. Here is an example of using npm for Laravel:

npm install --prefix resources/js @usecsv/js

Alternatively, you can reference the CDN directly in your Laravel's HTML:

<script src="https://unpkg.com/@usecsv/js/build/index.umd.js"></script>

Step 2: Create the importer button

To create your importer button, head over to your view and add the following html:

<button type="button" id="import-data-button" onclick="importData()">Import Data</button>

This will give you a basic import button that doesn't do anything yet.

Step 3: Add the JavaScript

To give your button CSV import capabilities through UseCSV, create a new file inside ressources/js/ - or add to where you keep your JavaScript - the following script:

importButton.onclick = function () { useCsvPlugin({ importerKey: "your-importer-key", user: { userId: "12345" }, metadata: { anotherId: "1" } }); };

This script will ensure that your CSV import button in Laravel is correctly connected up to your preconfigured importer data model.

UseCSV accepts three parameters: importerKey, user, and metadata. The importerKey is the only compulsory parameter because it identifies the target CSV importer.

The user and metadata parameters accept objects, which can be anything you want it to be. This is a good space to add any addition metadata that can help identify the source of the CSV import.

Step 4: Compile the JavaScript code and test

To use libraries that are in the resources/js folder, we need to compile them using Laravel Mix tool:

npm run dev

Now we can include the compiled JavaScript code in our views:

<script src="{{ mix('/js/app.js') }}"></script>

Once that's completed, you can now click on the import button. A modal will appear with the data model you've configured earlier.

Receive data from imports

We need to configure our web server. We'll be using the built-in PHP web server for this article. If you aren't already there, we just need to change into our project directory and start the server:

cd my-laravel-project php -S localhost:8000 -t public

This will start the web server on port 8000 of our local machine. The -t public option tells the server to serve files from the public directory.

Now that our server is up and running, let's create a simple route. Routes are used to map URLs to specific actions in your application. In Laravel, routes are defined in the routes/web.php file.

Open routes/web.php in your text editor and add the following route:

<?PHP Route::post('/endpoint', function (Request $request) { // });

In the route closure, we have access to the Request object. This object contains all the data that was sent to the endpoint. We can access this data using the following methods:

$request->all(); // Returns an array of all the data $request->input('key'); // Returns the value of the specified key

In our route closure, we will simply log out the received data:

<?PHP Route::post('/endpoint', function (Request $request) { Log::info($request->all()); });

Now, if we send a POST request to our endpoint, we should see the received data in our log file.

Save the file and visit http://localhost:8000 in your browser. You should see the "Hello, World!" string being printed.

Congratulations! You've just created you Laravel route and web server for importing CSV.

To connect this webhook endpoint up with your UseCSV importer, you can use a free Cloudflare tunnel.

cloudflared tunnel localhost:8080

If your Cloudflare commands are successful, you will get something like this:

2022-01-29T23:40:16Z INF Thank you for trying Cloudflare Tunnel. Doing so, without a Cloudflare account, is a quick way to experiment and try it out. However, be aware that these account-less Tunnels have no uptime guarantee. If you intend to use Tunnels in production you should use a pre-created named tunnel by following: https://developers.cloudflare.com/cloudflare-one/connections/connect-apps 2022-01-29T23:40:16Z INF Requesting new quick Tunnel on trycloudflare.com... 2022-01-29T23:40:17Z INF +--------------------------------------------------------------------------------------------+ 2022-01-29T23:40:17Z INF | Your quick Tunnel has been created! Visit it at (it may take some time to be reachable): | 2022-01-29T23:40:17Z INF | https://wan-attract-tin-exposure.trycloudflare.com | 2022-01-29T23:40:17Z INF +--------------------------------------------------------------------------------------------+

Use the tunnel link and paste it into the Webhook URL field to finish connecting everything up.

05.png

We're ready to try your first import

Make sure the Laravel server is running. Go to your localhost frontend and click on Import Data to open the importer modal.

Upload your CSV file, match the columns and then click import.

06.png 07.png 08.png

Watch your Laravel console log for the webhook payload. UseCSV will automatically split up the webhooks into batches of 1,000 rows.

Where to from here?

UseCSV makes it simple to add delightful CSV import to your app. There are many powerful features under the hood including themes and validation rules. Check out the docs for more info.

Add CSV Import To Your App

Get Started free and start integrating UseCSV today

Add CSV Import To Your App

Get Started free

and start integrating UseCSV today

Add CSV Import To Your App

Get Started free

and start integrating UseCSV today