2

I have a component table

<x-table :rows="$rowsArray"></x-table>

I pass array of arrays where each inner array represents <tr> row to be printed.

$rowsArray = [
  ['name'=>'Marko', 'age'=>21],
  ['name'=>'John', 'age'=>33]
]

Inside a component table.blade.php: I print each values as simple text

<table>
    @foreach($rowsArray as $tr)
        <tr>
            @foreach($tr as $td_key => $td_value)
                <td>
                    {{ $td_value }}
                </td>
            @endforeach
        </tr>
    @endforeach
</table>

As it is just printing string text, for situations I want different layout to be printed inside <td> I am passing layout through slot $customSlot.

Calling component with custom layout through slot

Hardcoded example ->

<x-table :rows="$rowsArray">
  <x-slot name="customSlot">
    <div class="flex">
      <span>
          Marko
      </span>
      <span>
          21 age
      </span>
    </div>
  </x-slot>
</x-table>

So updating code in table.blade.php I am checking if slot is passed, if not print string text.

<table>
    @foreach($rowsArray as $tr)
        <tr>
            @foreach($tr as $td_key => $td_value)
                <td>
                    @if(isset($customSlot))
                        {{ $customSlot }}
                    @else
                        {{ $td_value }}
                    @endif
                </td>
            @endforeach
        </tr>
    @endforeach
</table>

PROBLEM: I want to acces $tr data from current foreach iteration in slot scope, and not printing hardcoded values.

Here $tr['name'] and $tr['age'] are undefined, and I want it to be accessible from current iteration:

<x-slot name="customSlot">
    <div class="flex">
        <span>
            {{ $tr['name'] }}
        </span>
        <span>
            {{ $tr['age'] }} age
        </span>
    </div>
</x-slot>

Throws

$tr is undefined

Expected output from passed array:

<table>
    <tr>
        <td>
            <div class="flex">
                <span>Marko</span>
                <span>21 age</span>
            </div>
        </td>
        <td>
            <div class="flex">
                <span>John</span>
                <span>33 age</span>
            </div>
        </td>
    </tr>
</table>
Marko
  • 349
  • 2
  • 14

0 Answers0