Laravel 5 基础(十)- 日期,Mutator 和 Scope

php中文网
发布: 2016-08-08 09:26:45
原创
912人浏览过

在我们前面的解决方案中,直接给 published_at 赋值为当前日期实际上是一个临时解决方案,我们需要设定发布日期,可能是未来2天后才发布,让我们修改这个问题。

首先修改控制器:

<code>    public function store() {
        Article::create(Request::all());
        return redirect('articles');
    }</code>
登录后复制

然后修改视图,添加发布日期字段

<code>@extends('layout')

@section('content')
    <h1>Write a New Article</h1>

    <hr/>

    {{--使用我们添加的 illuminate\html 开源库--}}
    {!! Form::open(['url' => 'articles']) !!}
        <div class="form-group">
            {!! Form::label('title', 'Title:') !!}
            {!! Form::text('title', null, ['class' => 'form-control']) !!}
        </div>

        <div class="form-group">
            {!! Form::label('body', 'Body:') !!}
            {!! Form::textarea('body', null, ['class' => 'form-control']) !!}
        </div>

        <div class="form-group">
            {!! Form::label('published_at', 'Publish On:') !!}
            {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
        </div>

        <div class="form-group">
            {!! Form::submit('Add Article', ['class' => 'btn btn-primary form-control']) !!}
        </div>

    {!! Form::close() !!}

@stop</code>
登录后复制

ok,让我们添加一个新的文章,并且把日期设置为未来的某一天,但是文章直接显示在最开始了,这不是我们需要的。我们需要到了那天才显示出来。当然,我们需要更具体一点,比如在早上 8:00 显示,而不是0点显示。我们可以添加一个mutator(也就是其他语言的属性设置器),修改我们的model

<code><?php namespace App;

use DateTime;
use Illuminate\Database\Eloquent\Model;

class Article extends Model {

	protected $fillable = [
        'title',
        'body',
        'published_at'
    ];

    //属性设置其要遵守格式约定
    // set属性Attribute
    public function setPublishedAtAttribute($date) {
        $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date)->hour(8)->minute(0)->second(0);
    }

}</code>
登录后复制

添加一个新的纪录,查看数据库,我们已经将时间设置正确了,但是我们的首页仍然显示未来的才发布的文章,我们修改它。

<code>	public function index() {
        //$articles = Article::latest('published_at')->get();
        $articles = Article::latest('published_at')->where('published_at', '<=', Carbon::now())->get();

        return view('articles.index', compact('articles'));
    }</code>
登录后复制

上面的解决方法可以工作,但是查询语句太长了。我们可以使用 Laravel 提供的 scope ,来简化我们的工作。所谓scope可以理解为是查询过程中使用的中间查询结果,比如我们定义一个published scope,他可以返回所有当前已经发布的文章,让我们修改模型。

<code>    //设置scope,遵守命名规则
    public function scopePublished($query) {
        $query->where('published_at', '<=', Carbon::now());
    }</code>
登录后复制

修改控制器使用 scope

硅基智能
硅基智能

基于Web3.0的元宇宙,去中心化的互联网,高质量、沉浸式元宇宙直播平台,用数字化重新定义直播

硅基智能 62
查看详情 硅基智能
<code>	public function index() {
        //$articles = Article::latest('published_at')->get();
        //$articles = Article::latest('published_at')->where('published_at', '<=', Carbon::now())->get();
        $articles = Article::latest('published_at')->published()->get();

        return view('articles.index', compact('articles'));
    }</code>
登录后复制

结果相同,但在复杂的查询中我们可以使用scope来分解我们的任务,或者复用查询。

我们来增加一个新的查询,查询所有还没有发布的文章。在模型中添加scope

<code>    public function scopeUnpublished($query) {
        $query->where('published_at', '>', Carbon::now());
    }</code>
登录后复制

修改控制器使用unpulished

<code>	public function index() {
        //$articles = Article::latest('published_at')->get();
        //$articles = Article::latest('published_at')->where('published_at', '<=', Carbon::now())->get();
        //$articles = Article::latest('published_at')->published()->get();
        $articles = Article::latest('published_at')->Unpublished()->get();

        return view('articles.index', compact('articles'));
    }</code>
登录后复制

one more thing! 如果我们在 show 方法中使用 dd($article->published_at) 查看的结果,与 dd($article->created_at); 结果不一样,前者我们使我们自己的字段,后者是在 CreateArticleTable 中通过 $table->timestamp() 自动生成的。自动生成的字段显示出来是 Carbon类型,而我们的是字符串。使用 Crabon类型有很多的好处,例如你可以输出 dd($article->created_at->diffForHumans()); ,这种 1 hour ago 结果,但我们的published_at 不可以。怎么修改?修改模型,告诉laravel,published_at 是日期即可。

<code>    protected $dates = ['published_at'];</code>
登录后复制

再次使用 dd($article->published_at->diffForHumans()); ,结果显示为 3 days from now,Bingo!

以上就介绍了Laravel 5 基础(十)- 日期,Mutator 和 Scope,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号