1

I have a collection with a relationship in Laravel 5.4. I want to loop through it using a for loop.
If I do (testing):

{{ $application->kids[0]->name }}
{{ $application->kids[1]->name }}  

everything works.
But if I put index in kids array:

{{ $application->kids[$i]->name }}

it throws a 500 error.
I'm using native php loop: for($i = 0; $i < 5; $i++){}
What am I missing?

`<?php for($i = 0; $i < 5; $i++) { ?>  `

<input type="text" value="{{ $application->kids[$i]->name }}">   
<?php } ?>
3
  • 1
    Can you show your loop Commented Jun 20, 2017 at 22:32
  • Don't use native code in views. Post your model Commented Jun 20, 2017 at 22:44
  • Have you tried with blade @for($i = 0;$i < 2; $i++) ... @endfor ? Commented Jun 20, 2017 at 22:50

2 Answers 2

1

You may be iterating past the length of the $application->kids array and getting an ArrayOutOfBounds Exception. If you want to do a for loop I would suggest doing for($i = 0; $i < count($application->kids); $i++)

You may have better luck using a foreach within blade like so:

@foreach($application->kids as $kid)
  <input type="text" value="{{$kid->name}}"> 
@endforeach

More information on template control structures at https://laravel.com/docs/5.4/blade#loops

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

4 Comments

Even if it works it does not resolve the user's problem why using index crashes his page
Thanks. I know about this foreach but I'm trying to figure out what the problem is with for My question is why the iterator doesn't work while plain integer does.
Ah yes, it may be that you are iterating past the length of the array. So the array may only have 3 elements but you're iterating through 5. Thus hitting an array out of bounds exception. In your .env you can also update APP_DEBUG to true and see if that gives you more information.
@chip has solved the problem. While testing I was iterating through more items than I have in my array. Thank you.
0

use laravel foreach syntax to iterate over your data as

@foreach($application->kids as $kid)
  <input type="text" value="{{$kid->name}}"> 
@endforeach

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.