怎么在Laravel中实现一个手动分页功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
#vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:480 public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { $query = $this->toBase(); $total = $query->getCountForPagination(); $this->forPage( $page = $page ?: Paginator::resolveCurrentPage($pageName), $perPage = $perPage ?: $this->model->getPerPage() ); return new LengthAwarePaginator($this->get($columns), $total, $perPage, $page, [ 'path' => Paginator::resolveCurrentPath(), 'pageName' => $pageName, ]); }
从上面就可以看出,分页的关键就在于LengthAwarePaginator。
LengthAwarePaginator的构造方法。
public function __construct($items, $total, $perPage, $currentPage = null, array $options = []) { foreach ($options as $key => $value) { $this->{$key} = $value; } $this->total = $total; $this->perPage = $perPage; $this->lastPage = (int) ceil($total / $perPage); $this->path = $this->path != '/' ? rtrim($this->path, '/') : $this->path; $this->currentPage = $this->setCurrentPage($currentPage, $this->lastPage); $this->items = $items instanceof Collection ? $items : Collection::make($items); }
其实已经很明白了,假如要分页的数组为
[ ['username'=>'zhangsan', 'age'=>26], ['username'=>'lisi', 'age'=>23], ['username'=>'wangwu', 'age'=>62], ['username'=>'zhaoliu', 'age'=>46], ['username'=>'wangmazi', 'age'=>25], ['username'=>'lanzi', 'age'=>24], ['username'=>'pangzi', 'age'=>21], ]
共7条数据,每页显示3条,共3页
use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Pagination\Paginator; use Illuminate\Http\Request; # 仅做演示 # function userList(Request $request) { $users = [ ['username'=>'zhangsan', 'age'=>26], ['username'=>'lisi', 'age'=>23], ['username'=>'wangwu', 'age'=>62], ['username'=>'zhaoliu', 'age'=>46], ['username'=>'wangmazi', 'age'=>25], ['username'=>'lanzi', 'age'=>24], ['username'=>'pangzi', 'age'=>21] ]; $perPage = 3; if ($request->has('page')) { $current_page = $request->input('page'); $current_page = $current_page <= 0 ? 1 :$current_page; } else { $current_page = 1; } $item = array_slice($users, ($current_page-1)*$perPage, $perPage); //注释1 $total = count($users); $paginator =new LengthAwarePaginator($item, $total, $perPage, $currentPage, [ 'path' => Paginator::resolveCurrentPath(), //注释2 'pageName' => 'page', ]); $userlist = $paginator->toArray()['data']; return view('userlist', compact('userlist', 'paginator')); }
上面的代码中的重点是$item,如果不做注释1处理,得出的是所有7条数据。
注释2处就是设定个要分页的url地址。也可以手动通过 $paginator ->setPath('路径') 设置。
页面中的分页连接也是同样的调用方式:
{{ $paginator->render() }}
好了,基本就是这样,有纰漏的地方欢迎指正!
看看最终效果:
看完上述内容,你们掌握怎么在Laravel中实现一个手动分页功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。