16.分页

未匹配的标注

本节说明

  • 对应视频第 16 小节:Meta Infomation and Pagination

本节内容

首先我们改变一下话题显示的布局,如下:
file
修改布局文件如下:
forum\resources\views\threads\show.blade.php

@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8"> <div class="panel panel-default"> <div class="panel-heading"> <a href="#">{{ $thread->creator->name }}</a> {{ $thread->title }} </div> <div class="panel-body"> {{ $thread->body }} </div> </div> @foreach($thread->replies as $reply) @include('threads.reply') @endforeach @if (auth()->check()) <form method="post" action="{{ $thread->path() . '/replies' }}"> {{ csrf_field() }} <div class="form-group"> <textarea name="body" id="body" class="form-control" placeholder="说点什么吧..."rows="5"></textarea> </div> <button type="submit" class="btn btn-default">提交</button> </form> @else <p class="text-center">请先<a href="{{ route('login') }}">登录</a>,然后再发表回复 </p> @endif </div> <div class="col-md-4"> <div class="panel panel-default"> <div class="panel-body"> <p> <a href="#">{{ $thread->creator->name }}</a> 发布于 {{ $thread->created_at->diffForHumans() }}, 当前共有 {{ $thread->replies()->count() }} 个回复。 </p> </div> </div> </div> </div> </div> @endsection

注意$thread->replies()$thread->replies的区别:$thread->replies()返回的是一个hasMany对象,而$thread->replies返回的是一个Collection集合。

在本项目中,我们不仅想在show页面显示回复数量,而且想在index页面也进行显示。我们利用 Laravel 全局作用域 来实现。
forum\app\Thread.php

 . . class Thread extends Model { protected $guarded = []; protected static function boot() { parent::boot(); static::addGlobalScope('replyCount',function ($builder){ $builder->withCount('replies'); }); } . .

现在如果我们将$thread打印出来:
file
可以看到$thread多了一个replies_count属性。现在可以通过$thread->replies_count获取属性的方式获取回复数:
forum\resources\views\threads\show.blade.php

. . 当前共有 {{ $thread->replies_count }} 个回复。 . .

最后,我们来为回复加上分页参数:
forum\app\Http\Controllers\ThreadsController.php

. . public function show($channelId,Thread $thread) { return view('threads.show',[ 'thread' => $thread, 'replies' => $thread->replies()->paginate(10) ]); } . .

前端调用:
forum\resources\views\threads\show.blade.php

. . @foreach($replies as $reply) @include('threads.reply') @endforeach {{ $replies->links() }} . .

注:我们将每页回复数设为 10 ,所以当前无法看到分页效果。可将回复数设置为 1 查看效果。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
贡献者:1
讨论数量: 0
发起讨论 只看当前版本


暂无话题~