0
votes

I'm trying to use dompdf with Laravel, even though I use the 'use PDF' it's still error.

Here is my controller

<?php
    
namespace App\Http\Controllers;

use RealRashid\SweetAlert\Facades\Alert;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Pasien;
use Illuminate\Support\Facades\Redirect;

use PDF;
    
class PasienController extends Controller {
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $pasien = DB::table('pasien')->paginate(5);
        return view('pasien/index',  ['pasien' => $pasien]);
    }

    public function createPDF() {
        // retreive all records from db
        $data = Pasien::all();
  
        // share data to view
        view()->share('employee',$data);
        $pdf =  PDF::loadView('pdf_view', $data);
  
        // download PDF file with download method
        return $pdf->download('pdf_file.pdf');
    }
}

The PDF in this line is red

$pdf = PDF::loadView('pdf_view', $data);

The error display this message

Undefined type 'PDF'

I've put this in the providers

Barryvdh\DomPDF\ServiceProvider::class,

And this on the aliases

'PDF' => Barryvdh\DomPDF\Facade::class,

I've installed the package using composer, and also php artisan vendor publish it.

3
try config:cache command in case if you 've just installed the package - Khalid Khan

3 Answers

0
votes

In mine case it works

$pdf = \PDF::loadView('...');

I have added \ before PDF class name with loadView.

A \ before the beginning of a class name represents the Global Namespace.

0
votes

Maulik answer combined with Khalid khan really helped me, and it's actually worked!

INSTEAD OF

use PDF;

USE THIS(Even though I heard you can just use, 'use PDF'. But hey it works!)

use Barryvdh\DomPDF\PDF;

And then enter this command

php artisan config:cache

Reset everything, quit your IDE, restart your server, and then try opening your project again.

You can try clearing the cache first and then modifying your code, or one way another.

0
votes

I just added Barryvdh\DomPDF\ServiceProvider::class in my providers array (inside <path_your_project>/config/app.php) and 'PDF' => Barryvdh\DomPDF\Facade::class in my aliases array (inside the same file) and it worked for me!

Note1: I'm using Laravel 8.0.3

Note2: don't forget of run this:

composer require barryvdh/laravel-dompdf