Dark Cyber
Dark Cyber

Reputation: 2231

Laravel 5 : Nice way to generate table number?

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

Answers (2)

Aamer Shahzad
Aamer Shahzad

Reputation: 2947

Before this approach, I was using the following way to generate table numbering.

Studentscontroller

$students = Student::orderBy( 'name', 'asc' )
                     ->paginate( 20 );

return view( 'students.index', [
    'students' => $students,
    'total' => $students->total(),
    'perPage' => $students->perPage(),
    'currentPage' => $students->currentPage()
] );

students/index.blade.php

<td class="text-center">{{ ( $currentPage - 1 ) * $perPage + $key + 1 }}</th>

Upvotes: 4

ElefantPhace
ElefantPhace

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

Related Questions