Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only use created_at in Laravel

Tags:

php

laravel

I want only use created_at , how to do it?

I know:

This can custom timestamps name

const CREATED_AT = 'created';
const UPDATED_AT = 'updated';

This can disable timestamps

public $timestamps = false;
like image 789
refear99 Avatar asked Apr 27 '15 03:04

refear99


4 Answers

Eloquent does not provide such functionality out of the box, but you can create it on your own using the creating event callback:

class User extends Eloquent {

    public $timestamps = false;

    public static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->created_at = $model->freshTimestamp();
        });
    }

}
like image 167
Joseph Silber Avatar answered Nov 11 '22 03:11

Joseph Silber


Use on the top:

const UPDATED_AT = null;

And for 'created_at' field, you can use:

const CREATED_AT = null;

UPDATE FOR LARAVEL 5.5.0 - 5.5.5

This was broken in Laravel 5.5.0 (and fixed again in 5.5.5).

If you are using 5.5.x, make sure you are on the newest version.

If for some reason you cannot be on the newest version, here is a workaround.

Set the public $timestamps to false:

public $timestamps = false;

And when necessary:

public function setCreatedAtAttribute($value) { 
    $this->attributes['created_at'] = \Carbon\Carbon::now(); 
}

OR

public function setUpdatedAtAttribute($value) { 
    $this->attributes['updated_at'] = \Carbon\Carbon::now(); 
}

When the two fields "created_at" and "updated_at" are required, you do not have to do anything, of course ;)

like image 28
Rodolfo Jorge Nemer Nogueira Avatar answered Nov 11 '22 02:11

Rodolfo Jorge Nemer Nogueira


I have a better answer from here for Laravel 5.2 or above.

U can use this in model-

class User extends Model
{
    public $timestamps = false; // disable all behavior
    public $timestamps = true; // enable all behavior
    public $timestamps = [ "created_at" ]; // enable only to created_at
    public $timestamps = [ "updated_at" ]; // enable only to updated_at
    public $timestamps = [ "created_at", "updated_at" ]; // same as true, enable all behavior
}

So, for your question, the answer is -

public $timestamps = [ "created_at" ]; // enable only to created_at

Re-

public $timestamps = [ "created_at" ]; 

Not working in Laravel 6+

like image 37
Abrar Jahin Avatar answered Nov 11 '22 01:11

Abrar Jahin


My solution:

class CreatePostsTable extends Migration {

   public function up() {

      Schema::create('posts', function(Blueprint $table){

         $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
   });
}

This works for me

like image 21
Dan Avatar answered Nov 11 '22 01:11

Dan