Reputation: 1990
I have something like this in my controller passed to blade
$fields = [
'productCode' => [
'type' => 'text',
'validation' => 'required|min:4|max:10',
'label' => 'Product Code',
],
'productLine' => [
'type' => 'select',
'options' => ['Motorcycles' => 'Motorcycles', 'Classic Cars' => 'Classic Cars', 'Trucks and Buses' => 'Trucks and Buses'],
'validation' => 'required',
'label' => 'Product Line',
],
in my view blade
<?php
foreach ($fields as $field => $param):
$options = [];
if (!empty($param['options'])):
$options = $param['options'];
endif;
?>
<x-larastrap::{{ $param['type'] }}
name="{{ $field }}"
label="{{ $param['label'] }}"
<?php if (!empty($options)): ?>
:options="$options"
<?php endif; ?>
/>
<?php endforeach ?>
I am getting undefined variable $options but the $options value is being set (i can print_r and see the values. I suspect this has to do with how blade handles php expression. i can't seems to be able to figure out why
Upvotes: 2
Views: 138
Reputation: 640
Probably the best way to dynamically add components in your template is the "Dynamic Components" feature native of Laravel:
@foreach ($fields as $field => $param)
<x-dynamic-component
:component="sprintf('larastrap::%s', $param['type'])"
:params="[
'name' => $field,
'label' => $param['label'],
'options' => $param['options'] ?? null
]"
/>
@endforeach
This approach is also mentioned in the Larastrap documentation.
Upvotes: 0
Reputation: 138
the $options variable is encoded as a JSON string using json_encode. Then, within the Blade template, you can pass this JSON string as the options attribute, which will be decoded and used as needed.
@php
$options = json_encode($options); // Convert options to JSON string to pass to Blade template
@endphp
Upvotes: 0
Reputation: 1118
Your blade template does not follow the "Laravel" style of handling UI, modify your blade to this:
@foreach ($fields as $field => $param)
<x-larastrap::{{ $param['type'] }}
name="{{ $field }}"
label="{{ $param['label'] }}"
@if (!empty($param['options'])
:options="@json($param['options'])" <!-- or {!! json_encode($param['options']) !!} -->
@endif
/>
@endforeach
I've used json_encode()
to properly encode the $options
array for passing it to the component as a prop. This should ensure that the $options
variable is properly defined and passed to the component without any issues.
Upvotes: 1
Reputation: 11
Maybe you can try something like this
@foreach ($fields as $field => $param)
<x-larastrap::{{ $param['type'] }}
name="{{ $field }}"
label="{{ $param['label'] }}"
@if (!empty($param['options']))
:options="{{ json_encode($param['options']) }}"
@endif
/>
@endforeach
Upvotes: 0