PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 11, 2022

[FIXED] Override created_at value

 March 11, 2022     date, laravel, laravel-5, laravel-5.5, php     No comments   

Issue

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?


Solution

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;


Answered By - Robert
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing