A Step-by-Step Guide to Importing and Exporting CSV Files Using Laravel (Without Packages)

ArjunAmrutiya
3 min readAug 25, 2023

--

Introduction

In today’s data-centric world, the seamless import and export of data are essential for many applications. Laravel, a popular PHP framework, provides robust tools to facilitate CSV file import and export — an ubiquitous format for data exchange. In this guide, we’ll walk you through the process of importing and exporting CSV files using Laravel, step by step, without relying on external packages.

Step 1: Set Up a Laravel Project

Before you begin, make sure you have Laravel installed on your system. If not, install it using Composer:

composer global require laravel/installer

Create a new Laravel project:

laravel new CsvImportExport

Step 2: Create a Database and Model

Set up a database for your project and create a model that represents the data you’ll be working with. For instance, let’s assume you’re dealing with a “products” table. Generate the migration and model:

php artisan make:model Product -m

Step 3: Design the CSV Import Form

Create a form that allows users to upload a CSV file for import. In your view file (resources/views/import.blade.php), design the form:

<form action="{{ route('import') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="file" name="file" accept=".csv">
<button type="submit">Import CSV</button>
</form>

Step 4: Implement the CSV Import Logic

In your controller, handle the CSV import logic. Define a new route and method to manage the import:

use Illuminate\Http\Request;
use App\Product;

public function import(Request $request)
{
$file = $request->file('file');
$fileContents = file($file->getPathname());

foreach ($fileContents as $line) {
$data = str_getcsv($line);

Product::create([
'name' => $data[0],
'price' => $data[1],
// Add more fields as needed
]);
}

return redirect()->back()->with('success', 'CSV file imported successfully.');
}

Step 5: Create the CSV Export Logic

Now, let’s move on to exporting data to a CSV file. Define a route and method to manage the export:

use Illuminate\Support\Facades\Response;
use App\Product;

public function export()
{
$products = Product::all();
$csvFileName = 'products.csv';
$headers = [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $csvFileName . '"',
];

$handle = fopen('php://output', 'w');
fputcsv($handle, ['Name', 'Price']); // Add more headers as needed

foreach ($products as $product) {
fputcsv($handle, [$product->name, $product->price]); // Add more fields as needed
}

fclose($handle);

return Response::make('', 200, $headers);
}

Step 6: Design the Export Link

In your view, create a link that users can click to initiate the CSV export:

<a href="{{ route('export') }}">Export CSV</a>

Step 7: Test Your Import and Export Functionality

Run your Laravel development server:

php artisan serve

Visit the import form (http://localhost:8000/import) to upload a CSV file and test the import functionality. Use the export link to generate a CSV file containing the data from your database.

Conclusion

Congratulations! You’ve successfully implemented CSV import and export functionality using Laravel, all without relying on external packages. This hands-on approach gives you greater control over the process and enhances your understanding of how data can be managed within your Laravel applications

🌟 Enjoy my developer and blogging content? Support my work by buying me a virtual coffee on BuyMeACoffee! Your contributions help fuel insightful tech articles. Join hands in making coding more accessible and exciting for all. https://www.buymeacoffee.com/arjunamrutiya🚀

--

--

ArjunAmrutiya

👋 Hey there! I'm Arjun Amrutiya, a passionate web developer and blogger who loves all things PHP, Laravel and Vue.js. Welcome to my Medium account!