Do you want to export data from your database in your Laravel project? This tutorial presents a straightforward approach with which you can do that.

    This tutorial assumes that you are fairly comfortable with PHP and Laravel.

    Let’s get into it. You have a users table n your database. You want to export this table so you can maybe work on the data.

    Step 1. Create a controller for the data export

    php artisan make:controller ExportDataController

    Step 2: Create an Index method to take care of the data export.

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Models\User;
    class ExportDataController extends Controller
        public function index()
            $users = User::all();
            if (!empty($users)) {
                fopen('export.csv', 'w');
            return response()->download('export.csv');

    Now you have the controller that will query the database and export the data to CSV format. Next up is to create the route for the data export.

    Inside your route.php, add the route below.

    Route::get('/export', [\App\Http\Controllers\ExportDataController::class, 'index'])->name('export');

    That is how you export data from your Laravel application to Excel.


    Leave A Reply