Exporting data as a CSV file is a common requirement in Laravel applications. Follow this step-by-step guide to implement CSV export in Laravel using the Laravel Excel package.
Step 1: Install Laravel Excel Package
Run the following command to install the Laravel Excel package:
composer require maatwebsite/excel
Then, publish the package configuration:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Step 2: Create an Export Class
Generate an export class by running:
php artisan make:export UsersExport --model=User
Edit the generated file at app/Exports/UsersExport.php:
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all(); // Fetch all users
}
}
Step 3: Create an Export Controller
Generate a new controller:
php artisan make:controller ExportController
Edit app/Http/Controllers/ExportController.php:
namespace App\Http\Controllers;
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
class ExportController extends Controller
{
public function exportCSV()
{
return Excel::download(new UsersExport, 'users.csv');
}
}
Step 4: Define the Export Route
Add the following route in routes/web.php:
use App\Http\Controllers\ExportController;
Route::get('/export-users', [ExportController::class, 'exportCSV']);
Step 5: Add Export Button in Blade Template
In your Blade template (resources/views/users.blade.php), add this button:
<a href="{{ url('/export-users') }}" class="btn btn-primary">Download Users CSV</a>
Step 6: Run and Test the Export
Start your Laravel application:
php artisan serve
Now, open http://127.0.0.1:8000/export-users in your browser, and the **users.csv** file will be downloaded.
Conclusion
By following this guide, you have successfully implemented CSV export in Laravel. You can now customize the export logic based on your needs.
Visit Developer Sahayak
0 Comments