m2j
m2j

Reputation: 1160

parse array in laravel blade

my view page consist {{$data->attachment}} which render

[{"filename":"hello.jpg", "location":"/home/my_folder"}].

Here i tried to display file name in view page using

@foreach($data->attachment as $attachment)
   $attachment->filename
@endforeach

which gives me

Invalid argument supplied for foreach()

i trying

{{$data->attachment->filename}}

which gives me

Trying to get property of non-object

what i'm doing wrong? how can i display filename? thanks.

Upvotes: 1

Views: 4078

Answers (1)

tam5
tam5

Reputation: 3237

As you mentioned in the comments, the value of $data->attachment is actually a string. In order to iterate over it in a loop you will need to convert it back to an array.

So if you change your loop to:

@foreach(json_decode($data->attachment) as $attachment)
   {{ $attachment->filename }}
@endforeach

you should get what you want.

I would add that the correct place for this conversion should really be in your controller, not your view.

Your question was not entirely clear so this is all assuming you knew what you were doing when you used a foreach loop, meaning you actually have multiple entries in the $data->attachment array. If it is just the one attachment and you are really just trying to get the filename, then you don't need a loop, all you need is to say:

{{ json_decode($data->attachment)->filename }}

and again I would add that really that all belongs in your controller so that in your view you would end up with something like {{ $filename }}

Upvotes: 1

Related Questions