laravel5.1 阅读 2128
laravel5.1-第7.2章-简单blog-文章详情

laravel5.1-第7.2章-简单blog-文章详情

2023-06-28 • lulubin

一、注册路由

Route::get('/articles/{id}', 'ArticlesController@show');

二、修改方法

修改 ArticlesController.php 中的 show 方法

public function show($id)
{
   $article = Article::findOrFail($id);
   if(empty($article)){
       abort(404);
   }
   return view('articles.show',compact('article'));
}

注意:可以使用 dd() 打印数据

三、新建视图

新建文件:resources/view/articles/show.blade.php

https://file.lulublog.cn/images/3/2023/04/tk4g3EILzLIY5xiVi44I4Fz44ff84z.jpg?sign=cc613f4ca795dc74d27daeffedb67e04&t=6ad0f880

同时在 resources/view/app.blade.php 引入 bootstrap

https://cdn.bootcdn.net/ajax/libs/bootstrap/5.2.3/css/bootstrap.min.css

bootstrap 其他版本 https://www.bootcss.com/view.php?name=bootstrap

四、查看文章

http://localhost:8000/articles/3

https://file.lulublog.cn/images/3/2023/04/e9PVaQX4BqpaRFrXRzBbcRHKZaNbnF.png?sign=3c6b95e7e7ba7b0354774ddcc3f51c63&t=6ad0f880

五、修改文章列表视图

https://file.lulublog.cn/images/3/2023/04/F9kdK84kkKk102z0gl88lZ8VZ4lkF4.jpg?sign=02132251cd169de075dd4870bdf3b7a5&t=6ad0f880

有三种跳转方式:一般用 url 这种方式

六、$dates

修改 show 方法

public function show($id)
{
   $article = Article::findOrFail($id);
   if(empty($article)){
       abort(404);
   }
   dd($article->published_at->year);
   dd($article->created_at->diffForHumans());
   return view('articles.show',compact('article'));
}

Article 新增变量

protected $dates = ['published_at'];

这个让 published_at 也转换成 Carbon 对象