解決發布時間精確控制、查詢邏輯復用、日期物件自動轉換三大實戰問題。
表單提交 published_at 為日期 (如 2025-01-15),實際需在當天 08:00:00 發布,且列表頁僅顯示已發布文章。
// app/Article.php
use Carbon\Carbon;
protected $fillable = ['title', 'body', 'published_at'];
public function setPublishedAtAttribute($date) {
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date)
->hour(8)->minute(0)->second(0);
}
set{欄位名}Attribute (StudlyCase)$model->published_at = '2025-01-15' 賦值// 已發布文章
public function scopePublished($query) {
return $query->where('published_at', '<=', Carbon::now());
}
// 未發布文章
public function scopeUnpublished($query) {
return $query->where('published_at', '>', Carbon::now());
}
public function index() {
$articles = Article::latest('published_at')->published()->get();
// 等同:->where('published_at', '<=', Carbon::now())->get()
return view('articles.index', compact('articles'));
}
// 未發布列表
$articles = Article::latest('published_at')->unpublished()->get();
scope{名稱}$query (Builder 實例)protected $dates = ['published_at'];
效果:
$article->published_at->diffForHumans(); // "3 days from now"
$article->published_at->format('Y-m-d');
$article->published_at->addDay();
created_at, updated_at 預設已在基類 $datesTIMESTAMP/DATETIME,讀取自動實例化class Article extends Model {
protected $fillable = ['title', 'body', 'published_at'];
protected $dates = ['published_at'];
public function setPublishedAtAttribute($date) {
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date)
->hour(8)->minute(0)->second(0);
}
public function scopePublished($query) {
return $query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query) {
return $query->where('published_at', '>', Carbon::now());
}
}
Mutator 處理寫入、Scope 簡化讀取、$dates 強化日期操作,三者協作構建優雅的時間相關業務邏輯。