Search code examples
laraveleloquentdompdf

How to generate pdf after saving data in create view


I'm using barryvdh/dompdf wrapper for printing and saving PDF's, when I try to "Print" after inserting data to database it's not fetching last saved data to PDF.

I have tried fetching data by getting last saved id still no luck.

Print button of Main View:

<a href="{!! url('printPDF') !!}" target="_blank" class="btn btn-info">Print</a>

Controller:

 public function printPDF(Request $request)
    {
        $visID = MyModel::orderBy('id', 'DESC')->pluck('id')->first();
        $exi= $visID;
        $pdf = PDF::loadView('pdfview', compact('exi'));
        return $pdf->stream();
    }

pdfview:

<table>
    <tr>
        <th>First Name:</th>
        <td>{{ $exi['first_name'] }}</td>
    </tr>
    <tr>
        <th>Last Name:</th>
        <td>{{ $exi['last_name'] }}</td>
    </tr>
    <tr>
</table>

Getting only "First Name:" and "Last Name:" in print preview.


Solution

  • You've got a couple of issues that you could potentially improve. The first is that if you are hoping to get a collection of objects but are only using the method of first(), it will just give you a single instance. Using pluck further compounds this, as it won't give you the entire object, but just one field (id) in your example code:

    $visID = MyModel::orderBy('id', 'DESC')->pluck('id')->first();
    

    I suggest you change the above to get the full model. Remove pluck, add latest() if your db has the created_at field to support it:

    $exi = MyModel::latest()->first();
    

    or, you were on the right track, and can do it with the orderBy as well (Laravel's latest() is just syntactic sugar for the same thing - looks neat):

    $exi = MyModel::orderBy('id', 'DESC')->first();
    

    Then, instead of:

    $exi= $visID;
    

    You already have the last model within the variable from the query line above. After passing through to blade, you have all the data within $exi and can use object notation you wish:

    <tr>
         <th>First Name:</th>
         <td>{{ $exi->first_name }}</td>
    </tr>
    // etc