Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override created_at value

I'm trying to insert date into created at but nothing worked

I tried to use create as normal

$this->create([ 'product_id' => "$id", 'shop_name' => $shop,'created_at' => $date ]);

I tried to change the date format to match laravel

$date = date('Y-m-d H:i:s',strtotime($id['created_at']));

I also tried to user mutators to change the value each time

public function setFirstNameAttribute($value)
{
    $this->attributes['created_at'] = $value;
}

How can I set a specific date in created_at rather than the default date?

like image 375
Joumana Issa Avatar asked Feb 06 '18 20:02

Joumana Issa


1 Answers

Do you have fillable or guarded arrays set for your model?

If so, the create method will skip the fields that are not mass assignable.

If you want to fill in your own, you can do something like this:

$product = app(Product::class);
$product->timestamps = false; // disable timestamps for this creation

// set what you want to set
$product->product_id = $id;
$product->shop_name = $shop;
$product->created_at = $datetime; // <- datetime here
$product->save();

Although, if you look at the code (vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php), and the created_at field is fillable, it should not set another value if it was set during creation. (See the isDirty check there)


If you never wish to use the created_at and updated_at the normal way, just set timestamps to false in your model:

public $timestamps = false;
like image 83
Robert Avatar answered Sep 19 '22 01:09

Robert