Laravel Blade PHP Expression returns undefined variable

ghz 7months ago ⋅ 47 views

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

Answers

In Blade templates, PHP expressions should be enclosed within double curly braces {{ }}. However, when you are using PHP inside Blade directives like @foreach, @if, etc., you don't need to use <?php ?> tags.

Here's how you can modify your Blade template to avoid the undefined variable error:

@foreach ($fields as $field => $param)
    @php
        $options = [];
        if (!empty($param['options'])) {
            $options = $param['options'];
        }
    @endphp

    <x-larastrap::{{ $param['type'] }} 
        name="{{ $field }}" 
        label="{{ $param['label'] }}"
        @if (!empty($options))
            :options="{{ json_encode($options) }}"
        @endif
    />
@endforeach

In this modified version, I've replaced the <?php ?> tags with @php directive, and I've used Blade's @if directive instead of the PHP if statement. Also, I've used json_encode() to pass the $options array to the :options attribute if it's not empty.