how to fetch iterate number in blades foreach loop over collection - php

is there any way to fetch iterate number in blades foreach loop over collection ? I'm going to use it for selected drop down input default value . (i don't want to use "form model binding")
i try thesis and they does not work, maybe cause thesis for getting index value in foreach loop over objects :
key($theArrayYouAreLoopingThrough)
{{ #index }}
#foreach ($athletes as $key=>$athlete)
{{ ++$key }}
#endforeach
and so on.

If you're using 5.3 you can use $loop variable.
For example, to get current iteration, you can use inside #foreach or #for construction:
$loop->iteration

Related

how to limit data inside foreach value if there is condition applied?

In my blade template, I have applied foreach loop . And the data from foreach loop is from relation that I want to show. In that single loop I have to show three different type of data by applying IF condition. From my backend i have passed whole collection without limiting or pagination to front. And i want to limit data in my blade template.
blade view
#foreach($ft->menus as $menu)
#if($menu->foodtype_id == $ft->id)
//want to limti data here
// for every food type i want to show 6 data
#endif
#endforeach
controller page
$data['food_type'] = FoodType::with('menus')->get();
if i understood you correctly, you want to show 6 relationship rows for each food type. you have to check for current key in the loop then.
#foreach ($data['food_type'] as $ft)
#foreach ($ft->menus as $key => $menu)
#if ($key < 6)
{{ $menu->attribute }}
#else
#break
#endif
#endforeach
#endforeach
this will show you the first six rows from the relationship. and when it reaches the limit, it will break the foreach loop.
you can query the relationship too.
#foreach ($ft->menus()->limit(6)->get() as $menu)
{{ $menu->attribute }}
#endforeach

Laravel Get item syntax

I use Laravel with foreach in a blade.php
{{ $users = App\User::where('user_id', $post->user_id)->get() }}
and I got the result of this which show on the page
[{"user_id":"123","email":"123#com","password":"1234","first_name":"Tony"}]
But I want to get "Tony" only, how can I call?
{{ ($users = App\User::where('user_id', $post->user_id)->first())->first_name }}
Or better in sense of performance, if you select posts with user:
{{ $post->user->first_name }}
But it is better to prepare necessary data in controller.
get() returns an array, you should use first()
{{ ($users = App\User::where('user_id', $post->user_id)->first())->first_name }}
Since you said you are using foreach in blade. Try something like this
#foreach($user as $u)
{{$u->first_name}}
#endforeach
This will give you first_name for all users

Trying to get object of non-object. (Laravel)

I'm confused here. I've passed
$grade=Grade::all()->whereLoose('id',$gid);
from my controller.
When I access it in my view like:
#foreach($grade as $grade)
{{$grade->grade_name}}
#endforeach
It works fine. But when i try to use it again in my table:
#foreach($grade as $grade)
<tr class="success">
<td></td>
<td><b>Balance</b></td>
<td>{{$grade->fee_status}}</td>
#endforeach
It just throws Trying to get object of non object. What's the problem here? Can anyone help me?
You are reassigning $grade in your loop. It is now a single model. When you try to now iterate that you are iterating a single model which is not what you want to do (that will iterate the public properties of the object).
This will avoid that issue:
$grades = Grade::all()->whereLoose('id',$gid);
// different name for the variable for the current iteration
#foreach ($grades as $grade)
...
#endforeach
#foreach ($grades as $grade)
...
#endforeach
Watch the naming of variables.
On a side note, I am not sure why you are getting all the grades to just find the one with 'id' equal to $gid. If the id field is unique there should only be one and you wouldn't need to retrieve a collection.
$grade = Grade::find($gid);

Using in_array on collections

I need to check for a name in an array of names but I having trouble passing an array instead of a collection to the in_array() method.
My blade code looks something like this
#foreach($ecn->areas as $area)
{{ $area->area }}:<br>
<ul>
#foreach($area->people as $person)
#if(in_array($person, $ecn->signatures->name ))
<li><del>{{ $person }}</del></li>
#else
<li>{{ $person }}</li>
#endif
#endforeach
</ul>
#endforeach
I know my problem is in the way im trying to access the list of signatures.
#if(in_array($person, $ecn->signatures->name ))
I can access them in another part of the page doing this
#foreach($ecn->signatures as $signature)
{{ $signature->name }}<br>
#endforeach
and everything is fine.
How can I access and pass the list of signatures as an array in this scenario?
If you want to use in_array() version for Laravel Collections then you can use:
$collection->contains($needle)
It woks just like in_array.
If $needle is an integer, an id for example, don't forget to pluck first, like so:
$collection->pluck('id')->contains($needle)
You can use the lists or pluck method on the signatures collection to get a new collection of all the names. From there, you can either use the contains() method on the collection, or you can use the all() method to turn the collection into an array and use in_array directly.
I would suggest doing this outside of the foreach loop, so you're not generating this new collection and array every iteration.
Array:
// controller
$names = $ecn->signatures->lists('name')->all();
// blade
#if(in_array($person, $names))
Collection:
// controller
$names = $ecn->signatures->lists('name');
// blade
#if($names->contains($person))
You can also use contains() with a closure, which would let you get away with not creating an intermediate collection, but it's a little harder to read:
Contains with closure:
// blade
#if($ecn->signatures->contains(function ($key, $value) use ($person) {
return $value->name == $person;
}))
As per Laravel Docs
The get method returns an array of results where each result is an instance of the PHP StdClass object.
So you must convert your stdClass object to a array in your controller itself.
foreach ($ecn->signatures as $signature)
$nameArray[] = $signature->name;
and then you can use in_array in the blade template
#if(in_array($person, $nameArray))

Laravel Blade Templating #foreach order

Is there any way to sort #foreach loop in laravel blade?
#foreach ($specialist as $key)
<option value="{{$key->specialist_id}}"> {{$key->description}}</option>
#endforeach
I wolud like to order by $key->description,
I know I can use order by in my controller,
->orderBy('description')
but the controller returns other values and those values must be sorted as well, so I need to order by in blade.
Assuming that your $specialist variable is an Eloquent collection, you can do:
#foreach ($specialist->sortBy('description') as $oneSpecialist)
<option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
#endforeach
Moreover, you could call your Eloquent model directly from the template:
#foreach (Specialist::all()->sortBy('description') as $oneSpecialist)
<option value="{{ $oneSpecialist->specialist_id }}"> {{ $oneSpecialist->description }}</option>
#endforeach
Note that you are using a misleading variable name of $key in your foreach() loop. Your $key is actually an array item, not a key. I assume that you saw foreach ($array as $key => $value) syntax somewhere and then removed the $value?
I would suggest using a laravel collection. More specifically, the sortBy(). You can use either of these in your view or the controller that you are passing the data from. If the data is being passed by a model, be sure to use the collect() function before proceeding to use any of the others listed.
Hope this helps!
Even if the order fails you can use ->values() to re-index the elements
$collection->sortBy('key')->values()

Categories