Sulde1985 Sulde1985 - 11 days ago 6
PHP Question

Export PDF from Laravel

i'm trying to export a table in PDF, but I have a foreach and I want to export all data from foreach, but is not working for all, just for a row.

Here is the code:

foreach ($posts as $post) {
$html = '<div class="table-scrollable">
<table id="posts" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Title</th>
</tr>
</thead>
<tbody id="body"><tr>
<td>'
. $post->id . '
</td>
<td>' .
$post->name .
'</td>
<td>'
. $post->title .
'</td>
</tr>
</tbody>
</table>
</div>';
}
return PDF::load($html, 'A4', 'portrait')->download('my_pdf');

Answer

Inside foreach construct you override your $html variable, you need to initialize $html before foreach and add to end of string your html using Concatenation assignment .=

$html = '';
foreach ($posts as $post) {
        $html .= '<div class="table-scrollable">
                        <table id="posts" class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Name</th>
                                    <th>Title</th>
                                </tr>
                            </thead>
                            <tbody id="body"><tr>
                                <td>'
                . $post->id . ' 
                                </td>
                                <td>' .
                $post->name .
                '</td>
                                <td>'
                . $post->title .
                '</td> 
                    </tr>
                   </tbody>
                </table>
            </div>';
}
return PDF::load($html, 'A4', 'portrait')->download('my_pdf');
Comments