Get media collection spatie media library using inertia js

1.3k Views Asked by At

I'm using Spatie media library and I can upload images to storage and database. And I'm trying to display a media collection in a Vue component. This is my Controller:

public function showHotelPhoto($id)
{
    $hotel = Hotel::with('media');
    return Inertia::render('AdminHotelPhoto', [
        'data' => $hotel,
    ]);
}

And this my Vue component:

<template>
    <breeze-authenticated-layout>
        <template #header>
            <h2 class="font-semibold text-xl text-gray-800 leading-tight">
                Foto Hotel
            </h2>
        </template>


        @foreach ($hotel as $hotels)
            @foreach ($hotels->getMedia('property_images') as $image)
                <div class="-item">
                    <img src="{{ asset($image->getUrl()) }}">
                </div>
            @endforeach
        @endforeach


    </breeze-authenticated-layout>
</template>

<script>
import BreezeAuthenticatedLayout from '@/Layouts/Authenticated'

export default {
    components: {
        BreezeAuthenticatedLayout,
    },
    props: ['data'],
}
</script>

I know using @foreach can throw an error, but this is only for illustration. I want to loop get media collection in the Vue component.

1

There are 1 best solutions below

1
On

You should use v-for instead of @foreach. When you say with media, the media is returned as an array. You can access the path of the image with the original_url parameter in the directory.