Hi all, In this post, i will show you how we can download data in excel/CSV. Here I will use a package, which will do the job easily. Before i am going to deep, i expect you have knowledge of Laravel 9 installations, already have database and a project. Follow the below steps.
Step 1. Package installation
$ composer require maatwebsite/excel
Step 2. Create Controller and Route
Create a controller using below command , If you already have controller then no need.
$ php artisan make:controller YOUR_CONTROLLER_NAME
Create a function for export inside your controller
public function export_country(Request $req){ $adv_id=$req->adv_id; $campaign_id=$req->campaign_id; return Excel::download(new AdvCountryExport($adv_id, $campaign_id), 'CountryReport.xlsx'); }
Now write in Route file like below.
Route::POST("/export_country",[AdvertiserReportController::class,'export_country']);
Step 3. Create Export Class
Use the below command
php artisan make:export AdvCountryExport --model=AdvertiserReportModel
Now a new class is created inside App/Exports/AdvCountryExport
This will look something like below code.
<?php namespace App\Exports; use App\Models\AdvertiserReportModel; use Maatwebsite\Excel\Concerns\FromCollection; class AdvCountryExport implements FromCollection { /** * @return \Illuminate\Support\Collection */ public function collection() { return AdvertiserReportModel::all(); } }
Now change according to our need.
<?php namespace App\Exports; use Illuminate\Support\Facades\DB; use App\Models\AdvertiserReportModel; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; class AdvCountryExport implements FromCollection,WithHeadings { protected $adv_id, $campaign_id; function __construct($adv_id, $campaign_id) { $this->adv_id = $adv_id; $this->campaign_id = $campaign_id; } /** * @return \Illuminate\Support\Collection */ public function headings(): array { return [ 'Date', 'Country', 'Impressions', 'Clicks', 'CTR (%)', 'Spent', ]; } public function collection() { return collect(DB::select(DB::raw("SELECT sac_date, sac_country, SUM(sac_impressions) as imp, SUM(sac_clicks) as clicks, (SUM(sac_clicks)/SUM(sac_impressions))*100 ,SUM(sac_spent) as spent FROM `stats_adv_country` WHERE sac_adv_id=$this->adv_id AND sac_campaign_id=$this->campaign_id GROUP BY sac_country, sac_date ORDER BY sac_date DESC;"))); } }
Now run code when calling you routes you will get a file. Like below image