Laravel - Export CSV

version : Laravel 10
Post Time : 01-07-2024

Export CSV

install laravel
       - composer create-project --prefer-dist laravel/laravel:^10.0 laravel_demo

Create DemoController Controller  :
          - php artisan make:controller DemoController

app/Http/Controllers/DemoController.php

                                      
                                        

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Response;
use App\Models\Customer;


class DemoController extends Controller
{
   public function exportCSVDemo(Request $request)
   {
       return view('export_csv_demo');
   }
   public function exportCSV()
   {
       $customers = Customer::all();

       $csvData = '';
       $csvData .= "ID,Name,Email,Address,Phone No,Created At,Updated At\n";
       foreach ($customers as $customer) {
           $csvData .= sprintf(
               "%s,%s,%s,%s,%s,%s,%s\n",
               $customer->id,
               $customer->name,
               $customer->email,
               $customer->address,
               $customer->phone_no,
               $customer->created_at,
               $customer->updated_at
           );
       }
       $fileName = 'customers.csv';
       $headers = [
           'Content-Type' => 'text/csv',
           'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
       ];
       return Response::make($csvData, 200, $headers);
   }
}

Create Customer Model:
          - php artisan make:model Customer
app/Models/Customer.php

                                      
                                        

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
   use HasFactory;

   protected $fillable = [
       'name',
       'email',
       'address',
       'phone_no'
   ];

}

Create export_csv_demo blade file :-
Resources/views/export_csv_demo.blade.php

                                      
                                        

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
       <!-- Bootstrap CSS -->
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> 
</head>
<body>
   <div class="mb-3 row text-center">
       <h1>Export CSV</h1>
   </div>
   <div class="mb-3 mt-4 row  text-center" style="display:flrx; justify-content:center;">
       <div class="col-md-6">
           <a href="{{ route('exportCSV') }}" class="btn btn-primary">Export CSV</a>
       </div>
   </div>
</body>
</html>

routes/web.php

                                      
                                        

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DemoController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/
Route::get('/', function () {
   return view('welcome');
});

Route::get('/exportCSVDemo', [DemoController::class, 'exportCSVDemo'])->name('exportCSVDemo');
Route::get('/exportCSV', [DemoController::class, 'exportCSV'])->name('exportCSV');