CodeBriefly
Tech Magazine

How to Change The Naming of Datetime Fields in Laravel

0 782

Get real time updates directly on you device, subscribe now.

In this article, we will discuss how to change the naming of datetime fields in Laravel. As we know, Laravel provides rich features to fulfill our needs. It’s easy to change the naming of datetime fields.

 

Follow the example for change the naming of datetime fields

Assume, we have one migration for posts table or you can create with given artisan command.

php artisan make:migration create_post_table --create=post

After executing the above command, Our migration file is located at database/migrations.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

In this migration, $table->timestamps() add created_at and updated_at fields in the table. But the question is how to change those name? Yes, We can handle this in our model.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_on';

    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_on';
}

After defining the constant CREATED_AT and UPDATED_AT in the model. Now Laravel, use those columns instead of created_at and updated_at.

Hope you like this article, you can check more of Laravel tutorials. Feel free to add comments if any query.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More