Brainmaniac
Brainmaniac

Reputation: 2536

How to make a custom column with same properties as timestamp() columns?

I need a third column ( sorting_date ) with the same properties as the created_at and updated_at columns, they are both generated with timestamp().

I tried to do this in my migrations:

$table->datetime('sorting_date')->default(Carbon::now());

But that leaves me with a naked string of the date/time and hence I can't call all the goodie methods that exists for the two others eg. ->format('Y-m')

How can I add column 'sorting_date' and let it be an instance of the same class as created_at and updated_at?

Update

@PuriaDeveloper helped me with getting the column time to this:

$table->timestamp('sorting_date')->nullable()->default(Carbon::now());

But I still can't access the handy goodies attached to the carbon class.. Please see below my cut-outs from tinker:

>>>$i->sorting_date
=> "2019-01-25 11:09:57"
>>> $i->created_at
=> Illuminate\Support\Carbon @1548414597 {#3043
     date: 2019-01-25 11:09:57.0 UTC (+00:00),
   }
>>>

I need my column to produce the date wrapped in a carbon-collection! How is this done?

Upvotes: 0

Views: 77

Answers (2)

user10896277
user10896277

Reputation:

You need to add 'sorting_date' to $dates property of your model like this

class YourModel extends Model
{
    protected $dates = [
        'sorting_date',
   ];
}

For more details, check the docs here:

https://laravel.com/docs/5.7/eloquent-mutators#date-mutators

Upvotes: 1

Puria Golgoon
Puria Golgoon

Reputation: 216

You should use

$table->timestamp('sorting_date');

for more infomation check this link;

Upvotes: 1

Related Questions