简体   繁体   中英

Pagination output laravel blade

I'm a beginner in Laravel.

I need Paginate my Table with Data. Can't understand how setup links. I'm trying to search some documentation but don't understand how I can do this.

My Controller:

public function index()
    {
        $users = Viewers::all()->forPage(1, 5)->sortByDesc('last_activity');
        $users->setPath('/admin');
        return view('pages.admin.dashboard', ['users'=>$users]);
    }

My dashboard.blade.php :

@extends('layouts.admin')

@section('content')
    <div class="content">
        <table class="table">
            <thead>
            <tr>
                <th class="text-center">#</th>
                <th>IP</th>
                <th>Request URI</th>
                <th>Country</th>
                <th>City</th>
                <th>Device</th>
                <th>Last Activity</th>
            </tr>
            </thead>
            @foreach($users as $user)
                <tbody>

                <tr>
                    <td class="text-center">{{$user->id}}</td>
                    <td>{{$user->ip_address}}</td>
                    <td>{{$user->request_uri}}</td>
                    <td>{{$user->country}}</td>
                    <td>{{$user->city}}</td>
                    <td>{{$user->device}}</td>
                    <td>{{$user->last_activity}}</td>
                </tr>
                </tbody>
            @endforeach
        </table>
        <nav aria-label="Page navigation example">
            <ul class="pagination">
                <li class="page-item"><a class="page-link" href="#">Previous</a></li>
                <li class="page-item"><a class="page-link" href="#">1</a></li>
                <li class="page-item"><a class="page-link" href="#">2</a></li>
                <li class="page-item"><a class="page-link" href="#">3</a></li>
                <li class="page-item"><a class="page-link" href="#">Next</a></li>
            </ul>
        </nav>
    </div>
@endsection

Viewers::all() loads every record in your database into a Collection . Collections have sortBy() and sortByDesc() methods, but Models, which are Builder instances while querying, have an orderBy() method. Using DB ordering will in most cases be more efficient than PHP/Laravel sorting, so try not to use ::all() unless you need to.

With that being said, your query can be fixed to:

$users = Viewers::orderBy('last_activity', 'DESC')->paginate(100); // Replace 100 with desired number per page

Then, in your .blade.php file, use the links() method available on Pagination instances:

{{ $users->links() }}

That will output First, Previous, Page(s), Next and Last links, based on the number of records per page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM