Laravel的分页显示相对来说比较简单,首先咱们现在路由文件application/routes.php中定义路由:
Route::get('/', function() { // lets get our posts and eager load the // author $pre_page = 2;//每页显示页数 $posts = Post::with('author')->order_by('created_at', 'desc')->paginate($pre_page);//paginate($pre_page)及时查询数据时分页函数 // show the home view, and include our // 向模版返回数据 return View::make('pages.home')->with('posts', $posts); });
其次在模版中咱们这样做:
@section('content') @foreach ($posts->results as $post) <div class="post"> <h1>{{ HTML::link('view/'.$post->id, $post->title) }}</h1> <p>{{ substr($post->body,0, 120).' [..]' }}</p> <p>{{ $post->author->username }} {{ $post->created_at }}</p> <p>{{ HTML::link('view/'.$post->id, '阅读更多 →') }}</p> </div> @endforeach {{ $posts->links() }} @endsection
注意了,模版中数据库查询返回的记录放在$posts->results 中,所有要对$posts->results 遍历而不是$posts
最后使用{{ $posts->links() }}显示分页信息
因为Laravel默认使用的是en语言文件所有咱们相应使用中文分页提示的话,可以按如下步骤操作:
1.将项目中application/language/en复制一份重命名为“cn”
2.将application/config/application.php中的’language’ => ‘en’改为’language’ => ‘cn’;
3.将application/language/cn/pagination.php文件中的数组值汉化
4.汉化完成。