phplaraveldebuggingmpdf

Laravel 8 - ErrorException Undefined array key 2


I have the following foreach loop located within a Blade view to display an MPDF document.

@foreach($project->projectWarehouseProduct as $key => $pp)
    @php
        if($pp->unit == '2' || $pp->unit == '3'){
            $qtysentbox += $pp->qty;
    @endphp
    <tr>
        <td>...</td>
        <td>...</td>
        <td>...</td>
        <td>...</td>
    </tr>
    @php
        }
    @endphp
@endforeach

It shows error "ErrorException Undefined array key 2 on vendor/mpdf/mpdf/src/Mpdf.php:11801"

I already tried dd($project->projectWarehouseProduct) and the data exist and looks like this

Illuminate\Database\Eloquent\Collection {#368 ▼
  #items: array:28 [▼
    0 => App\Models\ProjectWarehouseProduct {#369 ▶}
    1 => App\Models\ProjectWarehouseProduct {#370 ▶}
    2 => App\Models\ProjectWarehouseProduct {#371 ▶}
    3 => App\Models\ProjectWarehouseProduct {#372 ▶}
    4 => App\Models\ProjectWarehouseProduct {#373 ▶}
    ....
  ]
}

But the data is still won't show. Even if the code inside foreach is emptied. it's still not worked. I also saw the code above the blade foreach, there's another loop with the same item, and it runs. Here's the code above the error one:

@php
    $adatile = false;
    $adalain = false;
    $qtysentbox = 0;
    $qtysentlain = 0;
    
    foreach($project->projectWarehouseProduct as $key => $pp){
        if($pp->unit == '2' || $pp->unit == '3'){
            $adatile = true;
        }
        if($pp->unit == '1' || $pp->unit == '4'){
            $adalain = true;
        }
    }
@endphp

How's that possible? and how to fix it? I need help.


Solution

  • You're getting "Undefined array key 2" because the Blade/PHP mix inside the loop is confusing Mpdf. Even if the raw data exists, the nested @php … @endphp blocks can break the PDF rendering. A straightforward fix is to use Blade conditionals instead of raw PHP inside your foreach. for example:

    @php
        $adatile = false;
        $adalain = false;
        $qtysentbox = 0;
        $qtysentlain = 0;
    
        foreach($project->projectWarehouseProduct as $pp){
            if ($pp->unit == '2' || $pp->unit == '3') {
                $adatile = true;
            }
            if ($pp->unit == '1' || $pp->unit == '4') {
                $adalain = true;
            }
        }
    @endphp
    
    @foreach ($project->projectWarehouseProduct as $pp)
        @if ($pp->unit == '2' || $pp->unit == '3')
            @php $qtysentbox += $pp->qty; @endphp
            <tr>
                <td>...</td>
                <td>...</td>
                <td>...</td>
                <td>...</td>
            </tr>
        @endif
    @endforeach
    

    To keep blade's templating clean, and avoid the parsing issue in Mpdf, Make sure $pp->unit and $pp->qty are normal string or integer fields, not arrays, and the PDF should render without the "Undefined array key 2" error.