Home > Net >  Laravel default CREATED_AT and UPDATED_AT column names don't change
Laravel default CREATED_AT and UPDATED_AT column names don't change

Time:12-02

I have a model Brand with a migration and I want to change the default timestamps' names to brandCreatedAt and brandUpdatedAt

I tried overriding the constants like below and migrating again but the table is still created with default timestamps name like created_at and updated_at

const CREATED_AT = 'brandCreatedAt';
const UPDATED_AT = 'brandUpdatedAt';

Migration -

public function up()
    {
        Schema::create('brands', function (Blueprint $table) {
            $table->id();
            $table->string('brandName')->nullable();
            $table->string('brandIsActive')->nullable();
            $table->timestamps();
        });
    }

Then I tried defining protected $table = 'brands'; but the issue remains. Then tried clearing cache with both artisan command and defining a route but no success. Maybe this is a small issue but I tried hours trying to find what's the issue but still I couldn't find it. TIA!

CodePudding user response:

Following what @Tim Lewis said, you should have files like these:

Model

class Brand extends Model
{
    // ...

    public const CREATED_AT = 'brandCreatedAt';
    public const UPDATED_AT = 'brandUpdatedAt';

    // ...
}

Migration

public function up()
{
    Schema::create('brands', function (Blueprint $table) {
        $table->id();
        $table->string('brandName')->nullable();
        $table->string('brandIsActive')->nullable();
        $table->timestamp(Brand::CREATED_AT);
        $table->timestamp(Brand::UPDATED_AT);
    });
}

CodePudding user response:

// Path: App\Models\Brand.php
class Brand extends Model
{
    use HasFactory;

    const CREATED_AT = 'brandCreatedAt';
    const UPDATED_AT = 'brandUpdatedAt';
}

// Path: database\migrations\..._create_brands_table.php
public function up()
{
    Schema::create('brands', function (Blueprint $table) {
        $table->id();
        $table->string('brandCreatedAt');
        $table->string('brandUpdatedAt');
        $table->timestamps();
        $table->dropTimestamps();
    });
}
  • Related