兩種情況:
使用 Model 的查詢
例如:
$item = App\Models\Apple::first(); $date = $item->created_at->format('Y-m-d');
使用 DB::table 的查詢
如果直接對結果中的 datetime 做 format,會報錯
Call to a member function format() on string
因為 DB::table 返回的結果都是 string,沒有關聯 Model。當然各種定義好的自動轉換也會失效。
這時候就需要先解析,再格式化
Carbon\Carbon::parse($item->expired_at)->format('Y-m-d')
最佳方案
所以,盡量使用 Model 進行數據查詢操作,避免使用 DB::table.
即使是使用 leftJoin 這些操作,也可以是 Model 進行。雖然官方文檔一直在用 DB::table.
例如:
$case->progress_detail = ProjectProgress::leftJoin('users', 'project_progress.pm_id', '=', 'users.id') ->select('project_progress.*', 'users.name') ->where('project_progress.id', $case->id) ->first();