davidkihara
davidkihara

Reputation: 533

How do I print foreach loop content within a controller?

I have this function that prints a PDF containing the fetched data. I tried loading the view to generate the PDF but it did not work, so I opted on loading the HTML which works fine. The problem is how i will print out the contents within the foreach loop. How do Iprint the item values?

    public function create( Request $request ) {
    $items = DB::table( 'products' )->get();

    $pdf = App::make( 'dompdf.wrapper' );
    $pdf->loadHTML( '<div class="container">
  <div class="row">
      <div class="col-md-8 col-md-offset-2">
          <div class="panel panel-default">
              <div class="panel-heading">Dashboard</div>
              <div class="panel-body">
                  <table class="table">
                      <thead>
                          <th>Product Name</th>
                      </thead>
                      <tbody>
                      foreach ($items as $item=>$key)
                        <tr>
                            <td>$key->name</td>
                        </tr>
                    endforeach
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
  </div>
  </div>
');
return $pdf->stream( 'quote.pdf' );
}

I recieved this outputin the pdf

Dashboard
Product Name$key->name

Upvotes: 0

Views: 467

Answers (1)

Ahmed Helal Ahmed
Ahmed Helal Ahmed

Reputation: 325

change this

     $pdf->loadHTML( '<div class="container">
  <div class="row">
      <div class="col-md-8 col-md-offset-2">
          <div class="panel panel-default">
              <div class="panel-heading">Dashboard</div>
              <div class="panel-body">
                  <table class="table">
                      <thead>
                          <th>Product Name</th>
                      </thead>
                      <tbody>
                      foreach ($items as $item=>$key)
                        <tr>
                            <td>$key->name</td>
                        </tr>
                    endforeach
                      </tbody>
                  </table>
              </div>
          </div>
      </div>
  </div>
  </div>
');

to

$html='<div class="container">
<div class="row">
    <div class="col-md-8 col-md-offset-2">
        <div class="panel panel-default">
            <div class="panel-heading">Dashboard</div>
            <div class="panel-body">
                <table class="table">
                    <thead>
                        <th>Product Name</th>
                    </thead>
                    <tbody>';

foreach ($items as $item=>$key) {
    $html.='<tr><td>'.$key->name.'</td></tr>';
}

$html.='  </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    </div>';

$pdf->loadHTML($html);

Upvotes: 1

Related Questions