Getting the position (index) of an object in foreach? - php

I have a simple foreach block in my view, like below.
#foreach ($teams as $key => $team)
{{ str_ordinal($key + 1) }}
#endforeach
Right now I'm displaying the key, although it isn't exactly accurate. Here's an image:
How can I display the actual position of the current iteration? I order by my teams collection but I'm not sure how I get the position of the current interation in that loop?

You can use $loop->index to get the index. Check its docs. For instance:
#foreach ($teams as $team)
{{ $loop->index }}
#endforeach
Will display 0,1,2,3,4... until the last element position.

You can apply array_values to your data before passing to template:
array_values($teams);
Or, according to this https://laravel.com/docs/5.6/blade#the-loop-variable, you can use special $loop variable. I suppose you need $loop->iteration property (it starts with 1) or $loop->index (starts with 0):
#foreach ($teams as $key => $team)
{{ $loop->iteration }}
#endforeach

#foreach($teams as $team)
<tr>
<td>{{ $loop->index+1}}</td>
<td>{{ $team->name}}</td>
<td>{{ $team->caption}}</td>
<td>{{ $team->address}}</td>
</tr>
#endforeach

Use a for loop instead of a foreach. You will get them in order.
$count = count($teams) ;
for($i=1;$i<=$count;$i++) {
// your code here using $i as the position
}

In Controller
foreach ($partners as $key => $partner) {
$data['id'] = $key + 1;
}

I have solved the same issue with the combination of built in loop variable and php directive
*this is wrong* You cannot use it directly in double curly braces
{{ $loop->index }}
Instead use it like this,
#foreach ($users as $user)
#php($count= $loop->index + 1)
<tr>
<th>{{ $count }}</th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->created_at }}</td>
</tr>
#endforeach
Though $loop variable is available inside foreach, you cannot use it inside the curly braces in blade template.

use this only it works fine {{$key+1}}

Related

laravel Property [id] does not exist on this collection instance

i cant access my admin_table i know i have and problem on my route on the admin_table please help me on my route Property [id] does not exist on this collection instance.
my admin_table.blade
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endforeach
</table>
this is my route
Route::get('/admin_table', 'DashboardController#index');
Route::put('/admin_table/{id}', 'DashboardController#store');
Route::get('/admin_table', 'DashboardController#show');
Route::get('/teacher_editform/{id}', 'DashboardController#edit');
Route::put('/teacher_editform/{id}', 'DashboardController#update')->name('teacheradminpage.teacher_tableform.teacher_editform');
this is my controller
public function edit($id)
{
$departments = Department::find($id);
$users = Schoolposition::find($id);
$students = Student::find($id);
$admins = Admin::find($id);
return view('teacheradminpage.teacher_tableform.teacher_editform', compact('departments','users','students','admins', 'id', 'id', 'id', 'id'));
}
Your issue is that you put an extra $position before the array. Your route should be
Edit
You've got several issues in this code that probably need attention. The main issue with the position error, seems to be that you've got a circular path to get that $position in your anchor tab within the loop.
This section is likely not creating what you want:
#foreach ($users as $positions)
#foreach ($positions->admins as $position )
This is roughly saying - take my collection of users and make a new collection of positions that are directly attached to each user object. From here, take that collection of positions and try and find a collection of admins on that are attached to that collection and then find a $position. (I think this is close to what it is trying to do...)
When you get to the inside of the loop and your anchor / route, you are asking the anchor to find an id on something that is likely either non-existent, or a collection again.
You have already passed in admins to this view. It would make sense to use that as your top level loop item, no?
To fix, use admins as the only loop item:
#foreach ($admins as $position )
Edit Your Blade With
#foreach ($users as $positions)
#if(!empty($positions->admins)
#foreach ($positions->admins as $position )
<tbody>
<tr>
<td>{{ $position->id}}</td>
<td>{{ $position->first_name}}</td>
<td>{{ $position->last_name}}</td>
<td>{{ $position->contact}}</td>
<td>{{ $position->departments->department}}</td>
<td>{{ $position->schoolpositions->school_position}}</td>
<td>{{ $position->email}}</td>
<th> Edit
</th>
</tr>
</tbody>
#endforeach
</tr>
</tbody>
#endforeach
#endif
#endforeach
</table>

Having problem with retriving json data in laravel

I'm working on a laravel project and i'm getting JSON error. I've try few options to solve the issue but did not come up with any solutions.
In this project I've to send multiple data into database onder one "ID". In that ID there are at list 10 data need to insert. So I used JSON format. It saves ok but getting error when I try to pull data.
Here is my code
Controller :
public function newExpenses(Request $request){
$Jexpenses = new Jexpenses;
$json = array(
'des' => $request->description,
'valu' => $request->expenses
);
$Jexpenses->voucher = $request->voucher_no;
$Jexpenses->date = $request->date;
$Jexpenses->description = json_encode($json);
$Jexpenses->expenses = $request->total;
$Jexpenses->remarks = $request->remark;
if($Jexpenses->save()){
$notification = array(
'message' => 'Expenses Saved',
'alert-type' => 'success'
);
}
return redirect()->back()->with($notification);
}
result :
{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}
Return Controller:
public function expenses(){
$data = array(
'title' => 'Expenses',
'expenses' => Jexpenses::all()
);
return view('expenses.expenses')->with($data);
}
html :
#foreach ($expenses as $key => $getData)
{{ $array = #json( $getData->description ) }}
<tr>
<td>{{ ++$key }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($array->description as $k => $v)
<td>{{ $array->des['$k'] }}</td>
<td>{{ $array->valu['$k'] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach
it should be work fine but getting error
error:
syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php
Need some help. Thanks.
1) Use json_decode($getData->description) instead #json. The #json is shortly form of json_encode
2) $array->description not exists property. Should be $array->des
3) You use variable in ' quotes. You should use " quote or nothing round variables.
4) It is bad idea using reserved words as variable names. I am about variable $array
#foreach ($expenses as $key => $getData)
{{ $descriptionData = json_decode( $getData->description ) }}
<tr>
<td>{{ $key + 1 }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($descriptionData->des as $k => $v)
<td>{{ $descriptionData->des[$k] }}</td>
<td>{{ $descriptionData->valu[$k] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach

Laravel foreach multiple data

This is how I wish to be
Actual
Status gets printed 3 times
I return this objects from my controller:
return view('ViewTicket') ->with('tickets', $tickets)
->with('user', $user)
->with('priority', $priority)
->with('status', $status)
->with('type', $type);
However I want to print the respective fields like in my view:
#foreach ($tickets as $t)
<tr>
<td> {{$t->id}} </td>
#foreach ($user as $u)
#if($t->user_id==$u->Id)
<td>{{ $u->UserName }}</td>
#endif
#endforeach
Even this doesnt solve my problem.Is there any way to avoid the loop inside the loop to get these data?The goal is to get respective fields for each ticket
If I dd($user) it returns 3 values okay
when I loop in my view it displays 9 values,which means it loops 3 times the lements
Thanks in Advance
ASSUMPTIONS
$tickets is a collection of ticket objects.
$user is a collection of user objects.
CODE
#foreach ($tickets as $t)
<tr>
#foreach ($user as $u)
#if($t->user_id == $u->Id)
<td> {{$t->id}} </td>
<td>{{ $u->UserName }}</td>
#endif
#endforeach
</tr>
#endforeach

foreach in blade template not working correctly

I'm having issues on displaying my data from foreach loop. I have 400+ thumbs on my database but laravel doesn't not work correctly, and my footer template didn't display too. I will put my code below.
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
myfooter code goes here.
from my controllers
$data['thumbs'] = thumb::all();
return View('tubetour/home',$data);
but when I tried to var_dump or return the value of thumbs on my controller
it displays all my 400+ data.
$data['thumbs'] = thumb::all();
return $data['thumbs'];
You need to pass an associative array as a second argument to the view function:
// Controller
$thumbs = Thumb::all();
return \View::make('tubetour.home', ['thumbs' => $thumbs]);
// View
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Edit: if you are using laravel 4 you will need to use View::make()
If Thumb is an Eloquent model, then the Thumb::all() will return an Eloquent collection, not an array. In that case you have to update your blade template like so:
#foreach($thumbs as $thumb)
{{ $thumb->name }}
{{ $thumb->desc }}
{{ $thumb->place }}
#endforeach
Hope this solve your issue.
UPDATE
Pass the $thumbs as an array and display it as table.
Update your controller like this:
$data['thumbs'] = thumb::all()->toArray();
return View('tubetour/home', $data);
And your view like this, see how many rows being displayed.
<table>
<thead>
<tr>Id</tr>
<tr>Name</tr>
<td>Desc</td>
<td>Place</td>
</thead>
<tbody>
#for ($i = 0; $i < count($thumbs); $i++)
<tr>
<td>{{ $i }}</td>
<td>{{ $thumbs[$i]['name'] }}</td>
<td>{{ $thumbs[$i]['desc'] }}</td>
<td>{{ $thumbs[$i]['place'] }}</td>
</tr>
#endfor
</tbody>
</table>
UPDATE 2
Blade template example with bootstrap grid:
<div class="row">
#for ($i = 0; $i < count($thumbs); $i++)
<div class="col-md-4">
<img src="img/sample.jpg">
<h3>{{ $thumbs[$i]['name'] }}</h3>
{{ $thumbs[$i]['desc'] }}
</div>
#endfor
</div>
try this
#foreach($data as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach
Update your controller
$data = Thumb::all();
return View::make('tubetour/home')->with("thumbs",$data)
->render();
Then your view with this:
#foreach($thumbs as $thumb)
{{$thumb['name']}}
{{$thumb['desc']}}
{{$thumb['place']}}
#endforeach

Laravel template with function?

I'm currently in the process of modernizing a legacy codebase and using Laravel.
The current infrastructure does something like this to print a value:
while($row = mysql_fetch_array($query) {
echo $row['value'];
}
All good... Easy to do in Laravel.
Except, it then does something like this...
while($row = mysql_fetch_array($query) {
echo $row['value'];
echo getValue($row['another_value']);
}
It calls another function to fetch the value each time in the loop and print the right value.
How can I replicate this or do the same thing without having a function in Laravel?
My code looks like this (blade's templating):
#foreach ($values as $value)
<td> {{ $value->value }} </td>
#endforeach
And obviously, this doesn't work:
#foreach ($values as $value)
<td> getValue({{ $value->value }}) </td>
#endforeach
The following code:
#foreach ($values as $value)
<td> getValue({{ $value->value }}) </td>
#endforeach
Should be like this:
#foreach ($values as $value)
<td>{{ getValue($value->value) }}</td>
#endforeach
Actually {{ }} print out anything (String) between those curly brackets, so {{ getValue($value->value) }} will be replaced with <?php echo getValue($value->value) ?>. Make sure that, your function returns a string value.

Categories