sharkyenergy
sharkyenergy

Reputation: 4173

Laravel - Eloquent - Get specific value from return array

I've following code:

     <div class="col-8
                    offset-2
                    mb-5
                    p-3
                    rounded-lg
                    shadow
                    d-flex
                    justify-content-between
                    align-items-baseline"
             style="background-color: lightgrey;
                 background-image: linear-gradient(to right, rgba(211, 211, 211, 0.52), rgba(211, 211, 211, 0.73)), url('/images/social_{{$gallery->photos->first()}}');  ">

the part of the code $gallery->photos->first() returns:

{"id":3,"gallery_id":1,"filename":"IMG_3700.png","filesize":4229181,"delete":0,"created_at":"2020-03-28T09:56:31.000000Z","updated_at":"2020-03-28T09:56:31.000000Z"}

I need to access the filename.. I tried a few things, but none of them worked:

$gallery->photos->first('filename')
$gallery->photos->first()->get('filename')
$gallery->photos->first()['filename']
$gallery->photos->first()->filename

the last attempt ($gallery->photos->first()->filename) returned this error:

Facade\Ignition\Exceptions\ViewException Trying to get property 'filename' of non-object (View: C:\xampp\htdocs\galshare\resources\views\home.blade.php)

how can I access the returned filename?

Thanks

Upvotes: 2

Views: 199

Answers (1)

Tpojka
Tpojka

Reputation: 7111

After some chat about this issue we came up with conclusion that $gallery sometimes returns an empty set which was reason for CSS rule to be angry (not having image URL in background-image rule). It was solved with one php block upfront where would be set default (fallback) image URL:

@php
$filename = '/path/to/default.jpg';
if ($gallery->isNotEmpty() && $gallery->photos->isNotEmpty()) {
    $filename = $gallery->photos->first()->filename;
}
@endphp
<style>
...
</style>

This block of code can also be done in controller from where can be sent $filename (i.e.) variable with value of $gallery->photos->first()->filename || '/path/to/fallback.jpg'.

Upvotes: 2

Related Questions