ARTICLE AD BOX
First, you have to put this inside your terminal in vscode. In my case, the project is about products. You just have to copy the flow. Just dont copy the whole thing.
composer require barryvdh/laravel-dompdfthen add something like this to your controller (for me this is a product controller)
use Barryvdh\DomPDF\Facade\Pdf; use Symfony\Component\HttpFoundation\StreamedResponse; public function exportPdf() { $products = Product::all(); $pdf = Pdf::loadView('product.pdf', compact('products')); return $pdf->download('products.pdf'); } public function exportCsv(): StreamedResponse { $headers = [ 'Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="products.csv"', ]; return response()->stream(function () { $handle = fopen('php://output', 'w'); fputcsv($handle, ['Name', 'Price', 'Description']); // headers row Product::chunk(100, function ($products) use ($handle) { foreach ($products as $product) { fputcsv($handle, [$product->name, $product->price, $product->description]); } }); fclose($handle); }, 200, $headers); }then add to web.php
Route::get('product/export/pdf', [\App\Http\Controllers\ProductController::class, 'exportPdf']) ->middleware(['auth', 'verified']) ->name('product.export.pdf'); Route::get('product/export/csv', [\App\Http\Controllers\ProductController::class, 'exportCsv']) ->middleware(['auth', 'verified']) ->name('product.export.csv');after that, create a view file (php artisan make:view product.pdf)
<!DOCTYPE html> <html> <body> <h2>Products List</h2> <table border="1" width="100%" cellpadding="5"> <thead> <tr><th>Name</th><th>Price</th><th>Description</th></tr> </thead> <tbody> @foreach ($products as $product) <tr> <td>{{ $product->name }}</td> <td>{{ $product->price }}</td> <td>{{ $product->description }}</td> </tr> @endforeach </tbody> </table> </body> </html>then finally, add button to your index file.
<a href="{{ route('product.export.pdf') }}" class="btn btn-danger">Export PDF</a>
<a href="{{ route('product.export.csv') }}" class="btn btn-success">Export CSV</a>
