Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMPDF loadView() error - undefined variable: data

I'm currently trying to incorporate the DOMPDF Wrapper for Laravel into my project, however I'm having troble figuring out how to pass a variable into the PDF template.

As per the instructions, in my controller I have:

//PrintController.php
$data = array('name'=>'John Smith', 'date'=>'1/29/15');

$pdf = PDF::loadView('contract', $data);
return $pdf->stream('temp.pdf');

and in my view:

//contract.php
...
<p><?php echo $data->name ?><p>
<p>Signature</p>

But when I try to render the page, I get the error:

ErrorException (E_UNKNOWN) 
Undefined variable: data

I'm not sure why the loadView() method is not passing the $data variable to the view. Is there a step I'm missing in setting it up in the controller and/or view?

like image 428
cchapman Avatar asked Jan 29 '15 14:01

cchapman


2 Answers

The loadView method you are using is going to use the extract method before passing the data to the views. This method extracts all the array elements, and creates variables for them based on the key of the element

This means that your array keys are going to be your variable names, ie $name and not $data->name. This is fairly standard in laravel, for example when using Blade Views.

http://php.net/manual/en/function.extract.php

like image 73
StephenMtl Avatar answered Oct 22 '22 22:10

StephenMtl


Use compact('data') instead of $data.

Example:

$pdf = \PDF::loadView('productType.invoice', compact('data'));
like image 32
RANJITH Avatar answered Oct 22 '22 20:10

RANJITH