上一节最后提到了表单验证,但是在做表单验证之前先介绍一些其他的内容。
一、添加日期
修改 store()
方法:
public function store(){ Article::create(Request::all()); return redirect('articles'); }
修改 app/views/articles/create.blade.php 模版,在提交按钮上面添加下面的字段:
<div class="form-group"> {!! Form::label('published_at', 'Publish on:') !!} {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!} </div>
现在再添加一篇新的文章,发现文章添加成功了,但是即使我们把发布日期设置为比现在将来的某一天,文章还是会直接显示出来。
二、Mutators
首先 Mutators 把日期处理下,修改 app/Article.php :
<?php namespace App; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Article extends Model { protected $table = 'articles'; protected $fillable = [ 'title', 'body', 'published_at' ]; public function setPublishedAtAttribute($date){ // 未来日期的当前时间 //$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date); // 未来日期的0点 $this->attributes['published_at'] = Carbon::parse($date); } }
方法命名规则: set + 字段名 + Attribute
,如果字段名中带有下划线,需要转成驼峰命名规则。下面解决文章提前现实的问题,修改控制器中的 index()
方法:
public function index(){ $articles = Article::latest('published_at')->where('published_at', '<=', Carbon::now())->get(); return view('articles.index', compact('articles')); }
这时再刷新页面,可以看到 published_at
比当前日期大的已经不显示了。不过每次需要查询发布的文章的时候,都需要加上 where('published_at', '<=', Carbon::now())
条件里那一大段,这样子太麻烦了。可以使用 Laravel 中的 scope 来优化该方法。
三、Scope
下面定义一个返回已发布文章的 scope ,修改模型文件 app/Article.php ,添加下面的方法:
public function scopePublished($query){ $query->where('published_at', '<=', Carbon::now()); }
接着修改控制器的 index()
方法,使用刚刚定义的 published
scope:
public function index(){ $articles = Article::latest('published_at')->published()->get(); return view('articles.index', compact('articles')); }
再次刷新页面,可以看到这个方法是起作用的。
四、Carbon日期
修改控制器的 show()
方法如下:
public function show($id){ $article = Article::findOrFail($id); dd($article->published_at); return view('articles.show', compact('article')); }
查看一篇文章的详细页,可以看到打印出来的就是普通的日期格式,而如果把 published_at
字段换成 created_at
的话,则会输出下面格式的信息:
上面就是Carbon格式。这种格式的好处是可以对日期数据进行处理:
// 返回当前日期加8天 dd($article->created_at->addDays(8)); // 对日期进行格式化 dd($article->created_at->addDays(8)->format('Y-m')); // 返回距离当前的时间,如: "3 day from now", "1 week from now" dd($article->created_at->addDays(18)->diffForHumans());
可以看到使用 Carbon 类型的日期有很多的好处,所以我们希望Laravel把我们定义的 published_at
也当作 Carbon 类型,只需要修改 Article.php 模型,添加下面的字段:
protected $dates = ['published_at'];
这时再打印出 published_at
的时候,可以看到已经被转换成 Carbon 类型了。
该篇属于专题:《Laravel 5 基础视频教程学习笔记》