Laravel & Php

Laravel Export file with Maatwebsite package and Using Native PHP.


Laravel Export file with Maatwebsite package and Using Native PHP.

To export data to a CSV file in Laravel, you can use a few different approaches. One common method is using the Laravel Excel package, which simplifies the process of exporting and importing data. Here’s how you can do it:

Step 1: Install the Laravel Excel Package

You need to install the Maatwebsite/Laravel-Excel package via Composer.

composer require maatwebsite/excel

Step 2: Create an Export Class

You can create an export class that will handle the data you want to export.

php artisan make:export UsersExport --model=User

This will create a new export class in app/Exports/UsersExport.php.

Step 3: Define the Export Logic

In the UsersExport class, you need to specify the collection of data you want to export. Here’s an example:

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return User::all();
    }
}

Step 4: Export the Data in a Controller

In your controller, you can now trigger the export process.

namespace App\Http\Controllers;

use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Export users to CSV.
     *
     * @return \Illuminate\Support\Facades\Response
     */
    public function export()
    {
        return Excel::download(new UsersExport, 'users.csv');
    }
}

Step 5: Set Up the Route

Finally, create a route to handle the export request.

use App\Http\Controllers\UserController;

Route::get('export-users', [UserController::class, 'export']);

Access the Export

Now, when you visit yourdomain.com/export-users, the users’ data will be downloaded as a CSV file.

Alternative Method: Using Native PHP

If you prefer not to use an external package, you can use native PHP functions like fputcsv. Here’s a quick example:

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class UserController extends Controller
{
    public function export()
    {
        $users = User::all();

        $filename = "users.csv";
        $handle = fopen($filename, 'w+');
        fputcsv($handle, ['ID', 'Name', 'Email']);

        foreach ($users as $user) {
            fputcsv($handle, [$user->id, $user->name, $user->email]);
        }

        fclose($handle);

        $headers = [
            'Content-Type' => 'text/csv',
        ];

        return Response::download($filename, $filename, $headers);
    }
}

This method is more manual but does not require additional dependencies.

Both methods will allow you to export data to a CSV file in Laravel.


Laravel Mysql PHP
Share with Friends

Like this chef? Share with friends..