skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. Your blade template does not follow the "Laravel" style of handling UI, modify your blade to this:

    @foreach ($fields as $field => $param)
        @php
            $options = !empty($param['options']) ? $param['options'] : [];
        @endphp
    
        <x-larastrap::{{ $param['type'] }}
            name="{{ $field }}"
            label="{{ $param['label'] }}"
            @if (!empty($options))
                :options="{{ json_encode($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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search