课程播放地址:http://www.erdangjiade.com/course/395.html
该老师讲课风格:
教师讲课深入浅出,条理清楚,层层剖析,环环相扣,论证严密,结构严谨,用思维的逻辑力量吸引学生的注意力,用理智控制课堂教学进程。教学的技巧,充满着机智,各种教学方法、技巧信手拈来,运用自如,恰到好处,并丝毫不带有雕琢的痕迹。
本视频中较为难点是Laravel-表单列表及分页实现:
在开发过程中有这么一种情况,你请求Java api获取信息,由于信息较多,需要分页显示。Laravel官方提供了一个简单的方式paginate($perPage),但是这种方法只适用model、查询构建器。
今天说下 给定一个数组如何实现 和paginate方法一样的效果。
查看paginate方法源码
#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 IlluminatePaginationLengthAwarePaginator;use IlluminatePaginationPaginator;use IlluminateHttpRequest; # 仅做演示 #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之表单篇视频教程的详细内容,更多请关注二当家的素材网其它相关文章!
友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群