How to "$set" Repeater itemLabel()

Select::make('quantity')
    ->options([
        '1' => 1,
        '2' => 2,
        '3' => 3,
        '4' => 4,
        '5' => 5,
    ])
    ->afterStateUpdated(function (Get $get, Set $set) {

        $name = array_fill(0, $get('quantity'), [
            'name' => '',
        ]);

        $set('members', $name);
    })
    ->live(),

Repeater::make('members')
    ->schema([
        TextInput::make('name')->required()->label('Name'),
    ])
    ->itemLabel("Student")
    ->hidden(fn (Get $get): bool => !$get('quantity'))
    ->addable(false)
    ->columns(1)
    ->collapsible()
    ->deletable(false)
    ->reorderable(false)
    ->live(),


Hi... I manage to set repeater number base on the Select::make('quantity') but how can I set itemLabel in afterStateUpdated?

Let say if the selected quantity is 3, the repeater will generate 3 Repeater TextInput with itemlabel value "Student" to all 3. How can I dynamically make it "Student 1", "Student 2", "Student 3"
image.png
Solution
Select::make('quantity')
->options([
    '1' => 1,
    '2' => 2,
    '3' => 3,
    '4' => 4,
    '5' => 5,
])
->afterStateUpdated(function (Get $get, Set $set) {

    $name = array_fill(0, $get('quantity'), [
        'name' => '',
    ]);

    $set('members', $name);
})
->live(),

Repeater::make('members')
->schema([
    TextInput::make('name')->required()->label('Name'),
])
->itemLabel(function (Get $get) {
    foreach ($get('members') as $key => $value) {
        Log::info($get('members'));
        return $key;
    }
})
->hidden(fn (Get $get): bool => !$get('quantity'))
->addable(false)
->columns(1)
->collapsible()
->deletable(false)
->reorderable(false)
->live(),


I did this but the foreach inside itemLabel will repeat entire array. Let say I select the quantity 2, then the loop log (Log::info($get('members'))) will look something like this

[2023-11-25 02:08:49] local.INFO: array (
  0 => 
  array (
    'name' => '',
  ),
  1 => 
  array (
    'name' => '',
  ),
)  
[2023-11-25 02:08:49] local.INFO: array (
  0 => 
  array (
    'name' => '',
  ),
  1 => 
  array (
    'name' => '',
  ),
)  


Lastly, what I did is I add another id array in afterStateUpdated and add another TextInput::make('id')->hidden() in the repeater schema then add ->itemLabel(fn (array $state): ?string => 'Student '.$state['id'] ?? null). Seem like confusing but here is the full code
Was this page helpful?