queryScope 和 setAttribute方法

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'));
    }

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

results matching ""

    No results matching ""