首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Laravel 5 日期處理、Mutator 與 Query Scope 進階應用

     編輯:PHP 相關知識

Laravel 5 日期處理、Mutator 與 Query Scope 進階應用

解決發布時間精確控制、查詢邏輯復用、日期物件自動轉換三大實戰問題。

問題背景

表單提交 published_at 為日期 (如 2025-01-15),實際需在當天 08:00:00 發布,且列表頁僅顯示已發布文章。

1. Mutator (設值器) 處理時間精度

// 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' 賦值
  • 統一補齊時分秒,避免控制器重複邏輯

2. Query Scope 復用查詢邏輯

// 已發布文章
public function scopePublished($query) {
    return $query->where('published_at', '<=', Carbon::now());
}

// 未發布文章
public function scopeUnpublished($query) {
    return $query->where('published_at', '>', Carbon::now());
}

控制器使用 Scope

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 實例)
  • 可鏈式呼叫多個 Scope
  • 語義化查詢,控制器極度簡潔

3. 日期欄位自動轉 Carbon ($dates)

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 預設已在基類 $dates
  • 自訂日期欄位加入此陣列即可享受 Carbon API
  • 資料庫存儲為 TIMESTAMP/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 強化日期操作,三者協作構建優雅的時間相關業務邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved