how to add index in laravel blade html attribute while calling collection - php

I am calling categories collection from controller and displaying in the blade in foreach loops
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="1">{{ $subcategory->name }}</a>
#endforeach
#endforeach
I need to add index numbers generated in the loop from 1 in data-column value
data-column="1"
data-column="2"
data-column="3"
so on....in

For doing this you need to make a variable for counting after that you should pass that variable to view like below.
I am inside a method
public function getSingle($slug){
$category= Post::where('slug','=',$slug)->first();
if ($post != null) {
$counter = 0;
return view('blog.single')->withCategories($category)->withCounter($counter);
} else {
return view('error.error404');
}
}
After that you should access that Counter variable in view like below
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{$counter++}}">{{ $subcategory->name }}</a>
#endforeach
#endforeach

The classic for will do
#foreach ($categories as $category)
#for ($i = 0; $i < count($category->subcategories); $i++)
<a class="a.toggle-vis" data-column="{{$i}}">{{ $category->subcategories[$i]->name }}</a>
#endfor
#endforeach

For a shorter one, I think, we can do something like this. A little bit dirty in view but in the small snippet, it should be okay.
{{ !($index = 1) }}
#foreach ($categories as $category)
#foreach ($category->subcategories as $subcategory)
<a class="a.toggle-vis" data-column="{{ $index++ }}">{{ $subcategory->name }}</a>
#endforeach
#endforeach

Use this simple solution (Laravel method):
$loop->iteration The current loop iteration (starts at 1).
It will automatically increment, in every loop iteration.
Check docs:
The Loop Variable

Related

Hiding results titles if there were no results

I have the following code that shows the output of a search for users, groups and posts :
<header><h1>Users results</h1></header>
#foreach ($users as $user)
#include('user.userblock')
#endforeach
<header><h1>Groups results</h1></header>
#foreach ($groups as $group)
#include('group.gruopblock')
#endforeach
<header><h1>Posts results</h1></header>
#foreach ($posts as $post)
#include('post.postblock')
#endforeach
How can I hide the <header> if one of them doesn't have results ?
Using eloquent #if and #endif with it s count() function:
#if(count($users))
<header><h1>Users results</h1></header>
#foreach ($users as $user)
#include('user.userblock')
#endforeach
#endif
#if(count($groups))
<header><h1>Groups results</h1></header>
#foreach ($groups as $group)
#include('group.gruopblock')
#endforeach
#endif
#if(count($posts))
<header><h1>Posts results</h1></header>
#foreach ($posts as $post)
#include('post.postblock')
#endforeach
#endif
#if (count($users))
<header><h1>Users results</h1></header>
#foreach ($users as $user)
#include('user.userblock')
#endforeach
#endif
and so on...
You've got several choices on how to do it thanks to the nature of the Laravel collection. But an if check conditional on either side will work fine:
if (empty($users)) { // Your header and foreach}
if ($users->first()) { // Your header and foreach}
if (!$users->isEmpty()) { // Your header and foreach}
if ($users->count()) { // Your header and foreach}

for loop with iteration in blade

i would like to know how to do in blade to have the equivalent of this code. I need to do an iteration inside a foreach . i see the blade loop variable like $loop->index or $loop->remaining but I need to know how to use it to make the equivalent of the code below.
<?php
for( $i = 0 ; $i < 3 ; $i++ ) {
$result[$i]['id'];
$result[$i]['name'];
$result[$i]['email'];
}
?>
Thank for any help
Thank mhrabiee. i found the solution.
#foreach($things as $thing)
#if( $loop->first or $loop->iteration <= 3 )
<tr>
<td>{{$thing)->id}}</td>
<td>{{$thing)->name}}</td>
<td>{{$thing)->email}}</td>
</tr>
#endif
#endforeach
this start first iteration
$loop->first
and this stop iteration after 3 loop
$loop->iteration <= 3
and voila !
Your question is a bit vague but exact equivalent of your code is something like this:
#for ($i = 0; $i < 3; $i++)
{{ $result[$i]['id'] }}
{{ $result[$i]['name'] }}
{{ $result[$i]['email'] }}
#endfor
By the way if you want to iterate through something like $results array you can do this:
#foreach ($results as $result)
<div>{{ $result->id }}</div>
<div>{{ $result->name }}</div>
<div>{{ $result->email }}</div>
#endforeach
PS: You can learn more about for loops in Laravel's Blade Documentation.

How to Count two array in foreach loop

Hi everybody here I have 2 paths so I return 2 arrays of tasks I need to count each array So in last I get
[6, 4]
#foreach ($path->pathtags as $Tag)
#foreach ($Tag->Tasks as $Task)
#if (!in_array($Task->id,$a))
<li class="list-group-item"> Task : {{ $Task->task_name }} </li>
#endif
#endforeach
#endforeach
Easiest php way of counting arrays is count($array) so if you want to make a new array with the 2 array counts you can do it like this:
$counts = [count($array1), count($array2)];
But if you need to count the records in the database, you will need to change the query instead of ->get() you will need to use ->count().
You should try this:
$path = count($path->pathtags);
$task = count($Tag->Tasks);
Updated answer
$path = count($path->pathtags);
#foreach ($path->pathtags as $Tag)
$task = count($Tag->Tasks);
#foreach ($Tag->Tasks as $Task)
<li class="list-group-item"> Task : {{ $Task->task_name }} </li>
#endforeach
#endforeach

How can I define variable array on the laravel blade view?

I try like this :
<div class="media-body">
#foreach($categories as $category)
#php $category[] = $category->name #endphp
#endforeach
{{ implode(",", $category) }}
</div>
If the code executed, there exist error :
undefine variable category
How can I solve it?
You can simply use Laravel Collection
{{ $categories->pluck('name')->implode(', ') }}
Or if you wanna do this in foreach then
#php ($names = [])
#foreach ($categories as $category)
#php ($names[] = $category->name)
#endforeach
{{ implode(', ', $names) }}
You have to declare an array within <?php ... ?> block and then use the same in a {{blade}} block.

How to display something only for the first item from the collection in Laravel Blade template

I have a #foreach loop in the Blade template and need to apply special formatting to the first item in the collection. How do I add a conditional to check if this is the first item?
#foreach($items as $item)
<h4>{{ $item->program_name }}</h4>
#endforeach`
Laravel 5.3 provides a $loop variable in foreach loops.
#foreach ($users as $user)
#if ($loop->first)
This is the first iteration.
#endif
#if ($loop->last)
This is the last iteration.
#endif
<p>This is user {{ $user->id }}</p>
#endforeach
Docs: https://laravel.com/docs/5.3/blade#the-loop-variable
SoHo,
The quickest way is to compare the current element with the first element in the array:
#foreach($items as $item)
#if ($item == reset($items )) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
Or otherwise, if it's not an associative array, you could check the index value as per the answer above - but that wouldn't work if the array is associative.
Just take the key value
#foreach($items as $index => $item)
#if($index == 0)
...
#endif
<h4>{{ $item->program_name }}</h4>
#endforeach
As of Laravel 7.25, Blade now includes a new #once component, so you can do it like this:
#foreach($items as $item)
#once
<h4>{{ $item->program_name }}</h4> // Displayed only once
#endonce
// ... rest of looped output
#endforeach
Laravel 7.* provides a first() helper function.
{{ $items->first()->program_name }}
*Note that I'm not sure when this was introduced. So, it may not work on earlier versions.
It is only briefly mentioned in the documentation here.
The major problem with Liam Wiltshire's answer is the performance because:
reset($items) rewind the pointer of $items collection again and again at each loop... always with then same result.
Both $item and the result of reset($item) are objects, so $item == reset($items) requires a full comparison of its attributes... demanding more processor time.
A more efficient and elegant way to do that -as Shannon suggests- is to use the Blade's $loop variable:
#foreach($items as $item)
#if ($loop->first) First Item: #endif
<h4>{{ $item->program_name }}</h4>
#endforeach
If you want to apply a special format to the first element, then maybe you could do something like (using the ternary conditional operator ?: ):
#foreach($items as $item)
<h4 {!! $loop->first ? 'class="special"': '' !!}>{{ $item->program_name }}</h4>
#endforeach
Note the use of {!! and !!} tags instead of {{ }} notation to avoid html encoding of the double quotes around of special string.
Regards.
if you need only the first element you can use #break inside your #foreach or #if.see example:
#foreach($media as $m)
#if ($m->title == $loc->title) :
<img class="card-img-top img-fluid" src="images/{{ $m->img }}">
#break
#endif
#endforeach
you can do it by this way.
collect($users )->first();
To get the first element of a collection in Laravel, you can use :
#foreach($items as $item)
#if($item == $items->first()) {{-- first item --}}
<h4>{{$item->program_name}}</h4>
#else
<h5>{{$item->program_name}}</h5>
#endif
#endforeach

Categories