Search code examples
laraveltimestampmigrationphp-carbon

laravel current timestamp in migration with carbon


I want to display created_at as a timestamp like this :

created_at : 1625501162

so this is my created_at column in migration:

$table->string('created_at')->Carbon::now()->timestamp;

Now I want this field to be created automatically when a new record is created and record the current time. so when i change the line to this :

$table->string('created_at')->useCurrent(Carbon::now()->timestamp);

gives me this error :

Method call is provided 1 parameters, but the method signature uses 0 parameters

so how can i fix this problem?

What other ways do you suggest for timestamp created_at and store it automatically?


Solution

  • If you want your column to be a timestamp you should use timestamp() instead of string(). useCurrent() doesn't take a parameter. Change

    $table->string('created_at')->useCurrent(Carbon::now()->timestamp);
    

    to

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

    https://laravel.com/docs/8.x/migrations#column-method-timestamp

    https://laravel.com/docs/8.x/migrations#column-modifiers

    Edit: to always get a timestamp instead of a date you can use

    protected $casts = ['created_at' => 'timestamp'];
    

    in your Model.