Using the Laravel Export CSV file tutorial today you will learn how to export CSV in Laravel. PHP has excellent features fopen, fputcsv and fclose options to generate a CSV file in Laravel or PHP framework without using any libraries.
In this example, we have added step by step simple way to export the product data in a CSV format. This Laravel Export CSV example will show you how to create CSV in the backend and will be accessible to download CSV file from the front end easily.
See Also: Laravel Import Large CSV file into the Database
#1 Download Laravel App
First, you need to download a new Laravel application using the following command.
composer create-project --prefer-dist laravel/laravel laravel-export-csv
Next, go inside the app:
cd laravel-export-csv
#2 Setup Database Credentials
Next, open the .env file and update the database credentials such as database name, username, password.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
#3 Generate Model & Migration
Now in this step, you need to generate the Product model and migration file using the following command.
php artisan make:model Product -m
Now, open the database/migrations/2023_04_20_161223_create_products_table.php file and update the below code on it.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('description')->nullable();
$table->decimal('price')->nullable()->default(0.00);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Next, run the migration using the below command to generate the products table with columns.
php artisan migrate
Now you need to update fillable properties in your newly created Product model. So open the app/Models/Product.php file and update the same as below.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'price', 'description'
];
}
#4 Create Routes
Next, open your routes/web.php file and add the following route. One is for showing the products list and the other is to create a logic to generate CSV in the backend and return the response to frontend.
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
Route::get('products', [ProductController::class, 'index']);
Route::get('products-export', [ProductController::class, 'export'])->name('products.export');
#5 Create Controller
Now, In this step, open your terminal and execute the following command to create the Product Controller.
php artisan make:controller ProductController
Now, go to app/http/controller/ProductController.php and update the following code in your controller file.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products', compact('products'));
}
public function export(Request $request)
{
$fileName = 'products.csv';
$products = Product::all();
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=$fileName",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$columns = array('Name', 'Price', 'Description');
$callback = function() use($products, $columns) {
$file = fopen('php://output', 'w');
fputcsv($file, $columns);
foreach ($products as $product) {
$row['Name'] = $product->name;
$row['Price'] = $product->price;
$row['Description'] = $product->description;
fputcsv($file, array($row['Name'], $row['Price'], $row['Description']));
}
fclose($file);
};
return response()->stream($callback, 200, $headers);
}
}
#6: Create Blade View File
Next, navigate the resources/views directory and create a new file named products.blade.php. Now open the resources/views/products.blade.php and update the following code on it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="pull-right">
<span data-href="{{ route('products.export') }}" class="btn btn-success btn-sm" onclick="exportProduct(event.target);">Export</span>
</div>
</div>
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
@foreach ($products as $product)
<tr>
<td>{{ $product->name }}</td>
<td>{{ $product->description }}</td>
<td>{{ $product->price }}</td>
</tr>
@endforeach
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function exportProduct(_this) {
const _url = $(_this).data('href');
window.location.href = _url;
}
</script>
</body>
</html>
#7 Generate Dummy Data using Laravel Facker & factory
So our laravel export CSV example functionality is almost completed, just need some dummy data in the products table. So we will add the test records using the Laravel Facker and factory.
Open the terminal create a Product Factory Class using the following command.
php artisan make:factory ProductFactory --model=Product
Now you can see in your database\factories\ProductFactory.php has a newly created file so open this file and update the same as the below code on it.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Product;
class ProductFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Product::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->title,
'price' => $this->faker->randomDigit,
'description' => $this->faker->text,
];
}
}
Execute the following command on command prompt to generate or create dummy data using tinker and factory command.
php artisan tinker
Product::factory()->count(20)->create()
#8 Run Dev server and Test
Now, it’s time to test our Laravel export CSV file example. So start your application using the serve command.
php artisan serve
After that hit the url in your browser.
http://localhost:8000/products
Conclusion
This Export CSV in Laravel was tested with the below Laravel version.
- Laravel 5
- Laravel 6
- Laravel 7
- Laravel 8
- Laravel 9
- Laravel 10