Laravel 08 文章列表页实现

  • 模型查找
//引入模型
user \App\Post;
//查找所有的数据,按时间排序,返回是对象形式;
$posts = Post::orderBy('created_at','desc')->get();
  • 页面渲染

phpstorm快速查找 文件 ctrl + shift + n

 @foreach($posts as $post)
                <div class="blog-post">
                    <h2 class="blog-post-title"><a href="/posts/{{$post->id}}">{{$post->title}}</a></h2>
                    <p class="blog-post-meta">{{$post->created_at->toFormattedDateString()}} by <a href="/user/5">Kassandra Ankunding2</a></p>

                    <p>{{$post['content']}}</p>
                    <p class="blog-post-meta">赞 0 | 评论 0</p>
                </div>
            @endforeach

工厂代码

//Post模型的数据填充函数
$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence(6),//6个字母
        'content' => $faker->paragraph(10),//10个句子
    ];
});

https://github.com/fzaninotto/Faker

php artisan tinker
// 创建预览
factory(App\Post::class,10)->make()
//插入数据库
factory(App\Post::class,10)->create()
  • 字符截断

str_limit(字符串,长度,超出部分代替字符)函数

@foreach($posts as $post)
   <div class="blog-post">
                    <h2 class="blog-post-title"><a href="/posts/{{$post->id}}">{{str_limit($post->title,30,'...')}}</a></h2>
                    <p class="blog-post-meta">{{$post->created_at->toFormattedDateString()}} by <a href="/user/5">Kassandra Ankunding2</a></p>

      <p>{{str_limit($post['content'],100,'..more..')}}</p>
      <p class="blog-post-meta">赞 0 | 评论 0</p>
   </div>
 @endforeach
  • 分页

post控制器中的index方法,调用分页函数paginate(单页的显示条数)

$posts = Post::orderBy('created_at','desc')->paginate(6);

在模板中 {{ $posts -> links() }}

{{$posts->links()}}

推荐阅读更多精彩内容