malvin18's avatar

Get media collection spatie media library using inertia js

I'm using spatie media library and I can upload images to storage and database. And I'm trying to display 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,i know using @foreach can throw an error , but this is only for illustration , i want to loop get media collection in 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>

can someone help me how to do it

0 likes
4 replies
JD45's avatar

I know this is a year old; however, I was searching for an answer and stumbled upon this as well. Here is how I solved it:

  1. Setup a Resource, in my case, BlogResource:
'blogs' => BlogResource::collection(Blog::activePosts())

Then in the Resource:

 'media' => $this->getFirstMediaUrl('blogs'),

Then was able to access the media via props: blog.media

1 like
sidjoshi2907's avatar

Or You can create your custom model & append the new attribute as a URL

use Spatie\MediaLibrary\Models\Media as BaseMedia;

class Media extends BaseMedia
{

    protected $appends = [
        'url'
    ];

    public function getUrlAttribute(): string
    {
        return $this->getUrl();
    }

}

Please or to participate in this conversation.