1

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.

7
  • try by $attachment = $data->attachment->toArray() and pass this $attachment variable to view and iterate foreach loop. Commented Mar 10, 2016 at 5:11
  • what do you get when you var_dump($data->attachment)? Commented Mar 10, 2016 at 5:21
  • as mentioned in the question [{"filename":"hello.jpg", "location":"/home/my_folder"}] Commented Mar 10, 2016 at 5:22
  • thats not a var_dump, what i am trying to say is does that echo out as a string or is it an object Commented Mar 10, 2016 at 5:23
  • 1
    Still you are allowed to use this method in view. Actually foreach needs array or object to iterate but you have JSON data. So try as below may it help: <?php $attachment = $data->attachment()->toArray(); ?> in your view Commented Mar 10, 2016 at 5:32

1 Answer 1

1

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 }}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.