Reputation: 2231
I can generate table number like this in my views index.blade.php
.
<?php $no = 1; ?>
@foreach($users as $user)
<td>{{ $no }}</td>
<td>{{ $user->username }}</td>
<?php $no++; ?>
@endforeach
and my controller is UsersController.php
public function index()
{
$users = User::all();
return view('admin.user.index')->withUsers($users);
}
Yes it work, but I think this not best practice and ugly to read since views only for interface not logic. I think something like pass data from controller or maybe you can answer with your ways.
Thanks, any help appreciated.
Upvotes: 0
Views: 7572
Reputation: 2947
Before this approach, I was using the following way to generate table numbering.
$students = Student::orderBy( 'name', 'asc' )
->paginate( 20 );
return view( 'students.index', [
'students' => $students,
'total' => $students->total(),
'perPage' => $students->perPage(),
'currentPage' => $students->currentPage()
] );
<td class="text-center">{{ ( $currentPage - 1 ) * $perPage + $key + 1 }}</th>
Upvotes: 4
Reputation: 3814
You could do this:
@foreach($users as $index => $user)
<td>{{ $index +1 }}</td>
<td>{{ $user->username }}</td>
@endforeach
Note the +1
since $index
will start at 0
Upvotes: 7