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

36 views Asked by At

my $gallery showing undefile 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

trying to get value from $images as $gallery in for each but it showing undefine, as $images getting value as expected but not getthing value as $gallery in foreach($images as $gallery).

1

There are 1 answers

0
Polash xaman On BEST ANSWER

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; ?>