How to Export Data to CSV or Excel Format in Laravel 9
- Step 1: Install Laravel Application
- Step 2: Configure Database in the .env file
- Step 3: Create Model, controller, and seeder file using a single command
- Step 4: Migrate the database and seed dummy data
- Step 5: Install the Excel package maatwebsite/excel
- Step 6: Create Routes
- Step 7: Create an export class
- Step 8: Create a Controller
- Step 9: Create a View
- Step 10: Run Laravel Application
Note: If you have already set up your laravel projects you can skip Step 1, Step 2, Step 3, and Step 4. else you can start from Step 1.
Step 1: Install Laravel Application
If you're not familiar with the process, you can refer to the "Install Laravel 9 from Scratch" tutorial. Alternatively, you can run the following command to proceed with this step:
composer create-project laravel/laravel laravel_export_app
Step 2: Configure Database in the .env file
After installing your Laravel application, it is necessary to create a database and configure the .env file appropriately. Below is an example that demonstrates how to configure your .env file:
Step 8: Create a Controller
Now open the App/Http/Controllers/PostController.php file and paste the below code.
Step 9: Create a View
Now create an index.blade.php file inside the resources/views/posts folder.
Step 10: Run Laravel Application
Now run the command below to run the app:
That's it, now you have all done open Chrome or any browser and hit URL Now open http://127.0.0.1:8000/posts or http://localhost:8000/posts.
If you are using this code after downloading from here make sure to run the bellow command then start your application.
Step 3: Create Model, controller, and seeder file using a single command
Step 4: Migrate the database and seed dummy data
Now Call it inside DatabaseSeeder.php
Then execute the following command to create all the tables and seed the dummy data defined in the PostSeeder class:
Step 5: Install the Excel package maatwebsite/excel
composer require maatwebsite/excel
If you are getting any issues with the above command you can run the below command to instal laravel excel package.
Step 6: Create Routes
Step 7: Create an export class
Now we have to create an export class using the below command
php artisan make:export PostExport --model=Post
Then define the functions inside it open App/Postexport.php and paste the below code
If you don't need a heading in your excel sheets then alternatively you can modify the above code like below.