美文网首页Laravel框架相关
[Laravel5.1教程]queryScope 和 setAt

[Laravel5.1教程]queryScope 和 setAt

作者: 7c03aed0f01f | 来源:发表于2016-11-30 16:11 被阅读200次

laravel 预处理

setAttribute

在模型中添加

namespace App;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Illuminate\Database\Eloquent\Model;

class News extends Model {
    protected $fillable = ['title', 'content', 'published_at'];

    /**
     * attribute 预处理
     * @param $data
     * 方法名组成: set + 字段名 + Attribute
     *
     */
    public function setPublishedAtAttribute($data) {
        $this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $data); //将published_at 这个字段补贴上详细时间
    }
}

将列表的数据 加条件

在控制器中添加

    public function index() {
        $result = News::latest()->where('published_at', '<=', Carbon::now())->get(); //控制发表的时间
        return view('news.index', compact('result'));
    }

还有一个简单的方法, 也可以时间上面的效果

相关文章

网友评论

    本文标题:[Laravel5.1教程]queryScope 和 setAt

    本文链接:https://www.haomeiwen.com/subject/sxstmttx.html