How to only use created_at in Laravel

2020-02-07 16:54发布

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;

标签: php laravel
17条回答
疯言疯语
2楼-- · 2020-02-07 17:17

To disable only updated_at, you can override Model::setUpdatedAt() method, like following :

public function setUpdatedAt($value) {
    // Do nothing.
}

Of course, if you wanted to do this for the created_at column, it's just as easy. And that's work for Laravel 5.1

查看更多
我只想做你的唯一
3楼-- · 2020-02-07 17:19

In Laravel 5.7, this was enough for me to have it work:

In migration:

$table->timestamp('created_at')->nullable();

instead of classic $table->timestamp('created_at');

In model:

const UPDATED_AT = null;
查看更多
我只想做你的唯一
4楼-- · 2020-02-07 17:22

For Laravel 5.*

Model:

//  Disable updated_at (only created_at)
class Book extends Model
{
     const UPDATED_AT = null;

     /* ... */
}

Migration:

Schema::create('books', function (Blueprint $table): void {
    /* ... */
    $table->timestampTz('created_at')->nullable();
});
查看更多
萌系小妹纸
5楼-- · 2020-02-07 17:24

In 5.4, the problem it gives is that it also doesn't populate updated_at field even after update (Eloquent update).

instead add this method

public function setUpdatedAtAttribute($value)
{
    // auto disable update_at in inserts 
}
查看更多
霸刀☆藐视天下
6楼-- · 2020-02-07 17:26

A solution that is simple, decoupled, and reusable is to use a Model Observer. The idea is to capture the creating event and fill the created_at attribute. This method may be used by any number of models without having to repeat code or using unofficial tricks. Most importantly, it closely resembles the internal mechanics of the Model class, thus avoiding unexpected errors.

1) Create SetCreatedAt observer in App\Observers:

namespace App\Observers;

use Illuminate\Database\Eloquent\Model;

class SetCreatedAt
{
    /**
     * Sets created_at when creating the model.
     *
     * @param Model $model
     * @return void
     */
    public function creating(Model $model)
    {
        $model->setCreatedAt($model->freshTimestamp());
    }
}

2) On App\Providers\AppServiceProvider inside the boot method add the following line for each of the models that you want the created_at to be generated for:

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    // Replace OrderLog with your model
    OrderLog::observe(SetCreatedAt::class);
}

3) On your models, the only thing that you have to do is disable the timestamps:

// Disable timestamps on the model
public $timestamps = false;

Tested with Laravel 5.3, but it should work with previous versions as well.

Good luck!

查看更多
登录 后发表回答