How to Export Specific Columns of a MySQL Table to a CSV File in Laravel
In Laravel, you can export a MySQL table to a CSV file by using the “SELECT” statement to retrieve the desired columns from the table and then using the “storeAs()” method of the Storage façade to write the data to a CSV file.
Here’s an example that exports the “id” and “name” columns from a table called “mytable” to a file called “myfile.csv”:
Fisrst we need usmanhalalit/laracsv
package to be able export data as file
composer require usmanhalalit/laracsv:^2.1
Then just write export function
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
...
$data = DB::table('mytable')->select('id', 'name')->get();
$csvExporter = new \Laracsv\Export();
$csvExporter->build($data, ['email'])->download('users_' . date("Y-m-d_h-i-s") . '.csv');
Alternatively you can use a package like maatwebsite/excel
to export the data to csv or exele with more flexibility
use Maatwebsite\Excel\Facades\Excel;
class MyController extends Controller
{
public function export()
{
return Excel::download(new MyTableExport, 'myfile.csv');
}
}
and in MyTableExport class
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class MyTableExport implements FromQuery, WithHeadings, ShouldAutoSize
{
public function query()
{
return DB::table('mytable')->select(['id', 'name']);
}
public function headings(): array
{
return ['id', 'name'];
}
}
In both of the examples above, you can replace “id” and “name” with the column names you want to export, and “myfile.csv” with the desired filename.
In conclusion, exporting a MySQL table to a CSV file in PHP or Laravel is a simple task that can be accomplished by using the “SELECT” statement to retrieve the desired columns from the table, and then using the “fputcsv()” function in PHP or the “storeAs()” method of the Storage façade or a package like maatwebsite/excel in Laravel to write the data to a CSV file. This allows you to easily export specific columns from a MySQL table and save the data to a CSV file for further analysis or use.