当前位置: 首页 > 后端技术 > PHP

Laravel5.4入门系列七、文章展示

时间:2023-03-29 23:02:42 PHP

文章展示功能比较简单,分为两部分:文章列表特定文章展示文章列表。之前已经定义了路由:Route::get('/posts','PostsController@index');控制器:publicfunctionindex(){$posts=Post::latest()->get();returnview('posts.index',compact('posts'));}latest()方法等同于:$post=Post::orderBy('created_at','desc')->get();最后是视图:/resources/views/posts/index.blade.php@extends('layouts.master')@section('content')@foreach($postsas$post)id])}}">{{$post->title}}{{$post->created_at->toFormattedDateString()}}通过

{{str_limit($post->body,20)}}

@endforeach<navclass="blog-pagination">Oldernewerstr_limit
@endsectioncreated_at该字段由迁移任务中的timestamps()方法生成,生成的时间为Carbon格式,表示你正在阅读或在编写时,Laravel会自动为你维护它。因此created_at也是Carbon的一个实例,可以使用Carbon包提供的各种方法进行进一步的操作。str_limit()是Laravel的一个辅助方法,用来截取一个字符串的前n个字符,然后返回前n个字符加上....的格式。显示一篇文章显示一篇文章比较简单,路由:Route::get('/posts/create','PostsController@create');Route::get('/post/{post}','PostsController@show');注意show应该放在create下,如果这样:Route::get('/post/{post}','PostsController@show');Route::get('/posts/create','PostsController@create');然后,当我们访问posts/create时,create会被当作show的查询参数。控制器:publicfunctionshow(Post$post){returnview('posts.show',compact('post'));}视图:/resources/views/posts/show.blade.php@extends('layouts.master')@section('content'){{$post->title}}{{$post->created_at->toFormattedDateString()}}byZen

{{$post->body}}

@endsectionCarbon-DateTime的简单PHPAPI扩展。