dwi prihta
dwi prihta

Reputation: 71

How to Change Date Format From Database In Controller Laravel 7

I tried to display data in the database, the date format in the database is like 2020-10-11T17: 22: 29.000000Z ", how can i change it just to 2020-10-11, or 11 December 2020 ?

This is my controller

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

This is my model

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

And this is the result

{
    "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"
        }
    ]
}

I just wana change the "created": "2020-12-11T20:46:23.000000Z", to "create":"2020-12-11", thanks for your answer guys :)

Upvotes: 1

Views: 4064

Answers (7)

Nono
Nono

Reputation: 7302

PHP Laravel Framework

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

Question

How to transform or change a table column's value/result on the fly e.g. format the timestamp into a date (y-m-d h:i:s) format?

Answer

Using Laravel Eloquent: Mutators & Casting helps the user to transform data values on the fly by defining them in the Model property.

Introduction

Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. Or, you may want to convert a JSON string that is stored in your database to an array when it is accessed via your Eloquent model.

Attribute Casting

Attribute casting provides functionality similar to accessors and mutators without requiring you to define any additional methods on your model. Instead, your model's $casts property provides a convenient method of converting attributes to common data types.

My table scema

enter image description here

My table data

enter image description here

My front result (before cast)

enter image description here

My front result (post cast)

enter image description here

My model file

<?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'
    ];
}

My controller (I've created controller inside a sub folder '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);
    }
}

My routes

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

My view (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>

Upvotes: 0

Max Brown
Max Brown

Reputation: 46

First way

Just add to the model:

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

Second way

You can individually customize the format of Eloquent date and datetime casting:

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

A few links that helped me to answer link one

A few links that helped me to answer link two

Upvotes: 0

STA
STA

Reputation: 34838

Laravel 7 uses a new date serialization format when using the toArray or toJson method on Eloquent models.

If you would like to keep using the previous behavior you can override the serializeDate() method on your model :

use DateTimeInterface;

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

See the official upgrade doc here [7.x]

Upvotes: 1

milad hedayatpoor
milad hedayatpoor

Reputation: 636

you cab use accessor for create_at and put this code in your model:

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

Upvotes: 0

Donkarnash
Donkarnash

Reputation: 12845

Laravel allows to specify the format in which datetime fields should be converted when serialized to array or json

Define $casts property on the model


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

Read more : https://laravel.com/docs/8.x/eloquent-mutators#date-casting

Upvotes: 0

OMR
OMR

Reputation: 12218

Eloquent Model has a property called cast to cast the output of the query to the desired format, in your case just cast your date columns like in doc:

class ArtikelKonten extends Model
{

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

Upvotes: 0

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1570

use date() for clear date and time formate

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

Upvotes: 0

Related Questions