phplaravel-bladefilepond

Showing undefine variable inside of foreach loop in php using laravel filepond


My $gallery showing undefined in laravel blade, but I am getting data on $images. I am using laravel with filepond

<?php if(count($images)): ?>
pond.setOptions({
    files: [
        <?php foreach($images as $gallery): ?> {
            source: "{{ asset('storage/' . $gallery->image) }}",
                options: {
                    id: "{{ $gallery->id }}",
                    type: 'local'
                },
            },
        <?php endforeach;?>
    ]
})
<?php endif;?>

The output image

I'm trying to get value from $images as $gallery in for each but it showing undefined, as $images getting value as expected but not getting value as $gallery in foreach($images as $gallery).


Solution

  • Indeed, it appears that I'm trying to embed PHP code within a JavaScript block, utilizing Blade templating syntax in the context of Laravel. The challenge here is the potential conflict between Blade's @foreach and JavaScript's curly braces.

    To address this issue, I've opted to use the @json directive. This directive is handy as it converts the PHP array into a JSON string, making it safe to include within the JavaScript code. Here's the updated version of the code I came up with: `

    <?php if (count($images)): ?>
        pond.setOptions({
            files: {!! json_encode($images->map(function ($gallery) {
                return [
                    'source' => asset("storage/{$gallery->image}"),
                    'options' => [
                        'id' => $gallery->id,
                        'type' => 'local',
                    ],
                ];
            })) !!}
        });
    <?php endif; ?>