Morteza Negahi
Morteza Negahi

Reputation: 232

Laravel Eloquent update created_at value

I need to change a post created_at because i send sms to posts created at this month according to created_at. When i try with this created_at does not change value!

public function Controller(Posts $post){
    $post->update(['created_at'=>Carbon::today()]);
}

Upvotes: 3

Views: 15407

Answers (4)

RyanT
RyanT

Reputation: 137

You can also use $guarded to allow all other attributes to be fillable

protected $guarded = ['id'];

See eloquent documentation on GuardsAttributes

Upvotes: 0

Don't Panic
Don't Panic

Reputation: 14520

created_at is not typically mass assigned like that. You probably need to add it to the $fillable attribute on your Post model, eg:

protected $fillable = [...., 'created_at']; 

Note that as someone else pointed out, Carbon::today() does not seem like the right thing to use - it works and gives a valid timestamp, but the timestamp is for midnight. You probably want Carbon::now(), if you really want the actual time of the change.

Upvotes: 10

Yat23
Yat23

Reputation: 171

Carbon::today() is not actually generating a valid timestamp. You need to use Carbon::today()->toDateTimeString() to get a valid timestamp.

Updated snippet:

public function Controller(Posts $post){
    $post->update(['created_at' => Carbon::today()->toDateTimeString()]);
}

Upvotes: 1

Milad Teimouri
Milad Teimouri

Reputation: 1211

try this

public function Controller(Posts $post){
      $post->created_at = Carbon::today();
      $post->save(['timestamps' => false]);
}

Upvotes: 1

Related Questions