0

In a blade template y controller passes a object which has few values in properties as bellow

value_L1 = "Hello"
value_L2 = "Stack"
value_L3 = "OverFlow"

I want to use a for loop to display these values but the statement in loop returns null, how can I do such a thing in blade?

@for ($count = 1; $count < 3; $count++)
    {{ $object->{'value_L.$count'} }}
@endfor

I am able to access these properties as following

{{ $object->value_L1 }}
{{ $object->value_L2 }}

Thanks,

K

karmendra
  • 2,206
  • 8
  • 31
  • 49
  • 3
    Single quotes will treat strings as literals, meaning your `$count` will be treated as a string `$count` not as the variable `$count`. Have a look [here](http://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php). – Andrei Oct 16 '15 at 15:26
  • Plus he has a dot between the `L` and the `$count` – Glad To Help Oct 16 '15 at 15:28
  • I saw this to access a property using a variable `$object->{'$var'}` where `$var="value_L1"` that worked. – karmendra Oct 16 '15 at 15:30
  • Doesn't ``$object->{'value_L'.$count}`` work? – rolandow Sep 14 '17 at 07:03

1 Answers1

3

How about

@for ($count = 1; $count < 3; $count++)
    {{ object_get($object, "value_L{$count}" ) }}
@endfor
Glad To Help
  • 5,299
  • 4
  • 38
  • 56
  • Excellent! Can you please mark it as correct answer? – Glad To Help Oct 16 '15 at 15:31
  • Yes I will, I am testing his edit, and also when i try `@if (isset(object_get($object, "value_L{$count}" )))` it gives syntax error – karmendra Oct 16 '15 at 15:36
  • do you have `@endif`? – Glad To Help Oct 16 '15 at 15:39
  • When I search on object_get I see no info on php.net or laravel documentation. Does it return false or null if property it is trying to access isn't available? – karmendra Oct 16 '15 at 15:45
  • Yes I have `@endif`, in fact I have a `@else` followed by `@endif` – karmendra Oct 16 '15 at 15:46
  • It is a laravel function, similar to `array_get()`, and also there is a third function called `data_get()` that works for both arrays and objects. You can take a look at it here http://laravel.com/docs/5.1/helpers#method-array-get – Glad To Help Oct 16 '15 at 15:48
  • and yes it will return false if you try to access a property that is not available. – Glad To Help Oct 16 '15 at 15:50
  • Right, I checked it returns null if property doesn't exist so now I can use it in if without isset. Thanks again. – karmendra Oct 16 '15 at 15:51
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92540/discussion-between-karmendra-and-glad-to-help). – karmendra Oct 16 '15 at 19:35