如何在控制器中更改数据库中的日期格式 Laravel 7

How to Change Date Format From Database In Controller Laravel 7

我试图显示数据库中的数据,数据库中的日期格式是 2020-10-11T17:22:29.000000Z",我如何将它更改为 2020-10-11,即 12 月 11 日2020 年?

这是我的控制器

 public function get_all_artikel(){
        $data = ArtikelKonten::select(
                'artikel_kategori.nama as kategori','artikel_konten.*')
                ->join('artikel_kategori','artikel_kategori.id','artikel_konten.id_kategori')
                ->get();
        if ($data){
         return response()->json([
                'status' => true,
                'artikel' => $data,
         ],200);}
         else{
             return response()->json([
                'status' => false,
                'message' => 'No Artikel were found'
         ],404);}
        }

这是我的模型

class ArtikelKonten extends Model
{
    
    protected $table = 'artikel_konten';
    protected $fillable = ['id_kategori', 'gambar', 'tag_program', 'nm_program', 'judul', 'preview', 'konten'];
    
    const CREATED_AT = 'created';
    const UPDATED_AT = 'modified';
}

这是结果

{
    "status": true,
    "artikel": [
        {
            "kategori": "Program",
            "id": 4,
            "id_kategori": "2",
            "tag_program": "2",
            "nm_program": "Zakat Mall",
            "gambar": "http://127.0.0.1:8000/storage/photos/1/article1.png",
            "judul": "Mengenalkan Zakat Kepada Anak",
            "preview": null,
            "konten": null,
            "created": "2020-12-10T07:24:50.000000Z",
            "modified": "2020-12-10T08:06:07.000000Z"
        },
        {
            "kategori": "Berita",
            "id": 10,
            "id_kategori": "1",
            "tag_program": "4",
            "nm_program": "Jumat Barokah",
            "gambar": "http://127.0.0.1:8000/storage/photos/1/article2.png",
            "judul": "Suplemen Iman Ditengah Pandemi",
            "preview": null,
            "konten": null,
            "created": "2020-12-11T20:44:25.000000Z",
            "modified": "2020-12-11T20:44:25.000000Z"
        },
        {
            "kategori": "Program",
            "id": 11,
            "id_kategori": "2",
            "tag_program": "2",
            "nm_program": "Zakat Mall",
            "gambar": "http://127.0.0.1:8000/storage/photos/1/article3.png",
            "judul": "Menumbuhkan Semangat Berzakat Umat",
            "preview": null,
            "konten": null,
            "created": "2020-12-11T20:46:23.000000Z",
            "modified": "2020-12-11T20:46:23.000000Z"
        }
    ]
}

我只是想将“created”:“2020-12-11T20:46:23.000000Z”更改为“create”:“2020-12-11”,谢谢大家的回答:)

使用 date() 明确日期和时间格式

date('d-m-Y', strtotime($value->created));

Eloquent 模型有一个名为 cast 的 属性 将查询的输出转换为所需的格式,在您的情况下,只需像 [=12= 中那样转换日期列]:

class ArtikelKonten extends Model
{

protected $casts = [
    'created' => 'datetime:Y-m-d','modified' => 'datetime:Y-m-d'
];
}

Laravel 允许指定日期时间字段在序列化为数组或 json

时应转换的格式

在模型上定义 $casts 属性


protected $casts = [
    'created_at' => 'datetime:Y-m-d',
    'updated_at' => 'datetime:Y-m-d',
];

阅读更多:https://laravel.com/docs/8.x/eloquent-mutators#date-casting

Laravel 7 在使用 toArraytoJson[=23 时使用新的日期序列化格式=] Eloquent 模型上的方法。

如果您想继续使用以前的行为,您可以覆盖模型上的 serializeDate() 方法:

use DateTimeInterface;

protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d');
}

查看官方升级文档here [7.x]

First way

只需添加到模型中:

  protected function asDateTime($value)
{
    return parent::asDateTime($value)->format('d/m/y');
}

Second way

您可以单独自定义 Eloquent 日期和日期时间转换的格式:

protected $casts = [
'created_at'  => 'date:Y-m-d',
'updated_at' =>  'datetime:Y-m-d H:00',];

A few links that helped me to answer

A few links that helped me to answer link two

您可以使用 create_at 的访问器并将此代码放入您的模型中:

    public function getCreatedAtAttribute($date)
{
    return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}

PHP Laravel 框架

Laravel Framework : 8.42.1
Date tested : 22 May 2021
PHP version : 7.3.8
Database : MariaDB 10.5.8
OS : MacOS 10.13.6 High Sierra

问题

如何动态转换或更改 table 列的 value/result 例如将时间戳格式化为日期 (y-m-d h:i:s) 格式?

回答

使用 Laravel Eloquent:Mutators & Casting 帮助用户即时转换数据值通过在模型 属性.

中定义它们

简介

访问器、修改器和属性转换 允许您在检索或设置它们时转换 Eloquent 属性值模型实例。例如,您可能希望使用 Laravel 加密器对存储在数据库中的值进行加密,然后当您在 Eloquent 模型上访问它时自动解密该属性。或者,您可能希望在通过 Eloquent 模型访问时将存储在数据库中的 JSON 字符串转换为数组。

属性转换

属性转换 提供类似于访问器和修改器的功能,无需您在模型上定义任何其他方法。相反,您的模型的 $casts 属性 提供了一种将属性转换为常见数据类型的便捷方法。

我的table场景

我的table数据

我的正面成绩(施法前)

我前面的成绩(post投)

我的模型文件

<?php
// app/Models/Post.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'description'
    ];

    // I've added this because I want to convert timestamp to 'y-m-d' on the fly
    protected $casts = [
        'created_at' => 'datetime:Y-m-d',
        'updated_at' => 'datetime:Y-m-d'
    ];
}

我的控制器(我在子文件夹 'API' 中创建了控制器)

<?php
// app/Http/Controllers/API/PostController.php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use App\Models\Post;

use Illuminate\Http\Request;

use Validator;

class PostController extends Controller
{
    // all posts, I'm calling this be the default
    public function index()
    {
        $posts = Post::all()->toArray();
        return array_reverse($posts);
    }
}

我的路线

<?php
// routes/api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\PostController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('posts', [PostController::class, 'index']);
Route::group(['prefix' => 'post'], function () {
    Route::post('add', [PostController::class, 'add']);
    Route::get('edit/{id}', [PostController::class, 'edit']);
    Route::post('update/{id}', [PostController::class, 'update']);
    Route::delete('delete/{id}', [PostController::class, 'delete']);
});

我的看法(Vue)

<template>
    <div>
        <h3 class="text-center">All Posts</h3><br/>
 
        <table class="table table-bordered table-responsive">
            <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Description</th>
                <th>Created At</th>
                <th>Updated At</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="post in posts" :key="post.id">
                <td>{{ post.id }}</td>
                <td>{{ post.title }}</td>
                <td style="width: 30%">{{ post.description }}</td>
                <td>{{ post.created_at }}</td>
                <td>{{ post.updated_at }}</td>
                <td>
                    <div class="btn-group" role="group">
                        <router-link :to="{name: 'edit', params: { id: post.id }}" class="btn btn-primary">Edit
                        </router-link>
                        <button class="btn btn-danger" @click="deletePost(post.id)">Delete</button>
                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>
 
<script>
    export default {
        data() {
            return {
                posts: []
            }
        },
        created() {
            this.axios
                .get('/api/posts')
                .then(response => {
                    this.posts = response.data;
                });
        },
        methods: {
            deletePost(id) {
                this.axios
                    .delete(`/api/post/delete/${id}`)
                    .then(response => {
                        let i = this.posts.map(item => item.id).indexOf(id); // find index of your object
                        this.posts.splice(i, 1)
                    });
            }
        }
    }
</script>