A
A
acspro2017-03-11 07:04:04
MySQL
acspro, 2017-03-11 07:04:04

How to execute a query in migration after adding a field of the DateTime type, fill it with the value from created_at?

Hello. I am learning Laravel. I'm doing a blog. There is a table with posts. I made a migration in which I add a new field published_at of DateTime type.

$table->dateTime('published_at')->after('status')->nullable();

I need to make this field not empty by default. If you use default - I can only enter specific values. And I would like that the values ​​were automatically entered from created_at when the field was added.
I tried to add this code and of course it didn't work:
DB::raw('UPDATE `news` SET `published_at`=`created_at`');
            $table->dateTime('published_at')->nullable(false)->change();

Tell me how to do it right, dear gurus.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Paul Denisevich, 2017-03-11
@deniamnet

Make a field mutator in the model by writing the current timestamp from Carbon there:

public function setPublishedAtAttribute($value)
{
    $this->attributes['published_at'] = ( ! empty($value)) ? $value : Carbon::now();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question