im@markvi.eu

In Lar­avel, you can export a MySQL table to a CSV file by using the SELECT” state­ment to retrieve the desired columns from the table and then using the store­As()” method of the Stor­age façade to write the data to a CSV file.

Here’s an exam­ple that exports the id” and name” columns from a table called mytable” to a file called myfile.csv”:

Fisrst we need usmanhalalit/laracsv pack­age 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');

Alter­na­tive­ly you can use a pack­age 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 MyTable­Ex­port 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 exam­ples above, you can replace id” and name” with the col­umn names you want to export, and myfile.csv” with the desired filename.

In con­clu­sion, export­ing a MySQL table to a CSV file in PHP or Lar­avel is a sim­ple task that can be accom­plished by using the SELECT” state­ment to retrieve the desired columns from the table, and then using the fputcsv()” func­tion in PHP or the store­As()” method of the Stor­age façade or a pack­age like maatwebsite/​excel in Lar­avel to write the data to a CSV file. This allows you to eas­i­ly export spe­cif­ic columns from a MySQL table and save the data to a CSV file for fur­ther analy­sis or use.

Similar Articles