How to set TimeStamp with Timezone in Laravel 5 Mi

2019-09-12 10:50发布

问题:

I had set timestamp in migrate laravel 5, like this:

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

But, that is no set with timezone in postgresql. I want to set timestamp with timezone in postgresql, how to do it?

回答1:

There is now a timestampsTz function available when using Postgres. It should be available in Laravel 5.1 and above.



回答2:

I had fix my problem.. I add a few code in laravel vendor directory

First step, open

vendor/laravel/framework/src/illuminate/Database/Schema/Blueprint.php

then, add this:

public function timestampz($column)
{
    return $this->addColumn('timestamptz', $column);
}

After that, open

vendor/laravel/framework/src/illuminate/Database/Schema/Grammars/PostgresGrammar.php

then, add this:

 protected function typeTimestamptz(Fluent $column)
    {
        return 'timestamp(0) with time zone';
    }

How to use: In your migration file, that is like this:

$table->timestampz('yourcolumntimestampwithtimezone');

UPDATE

  1. Create file in app/Custom, give it name CustomBlueprint.php. If you have no Custom directory, just create first.

CustomBlueprint.php :

namespace App\Custom;

use Illuminate\Database\Schema\Blueprint;

class CustomBlueprint extends Blueprint {

    public function timestampz($column)
    {
        return $this->addColumn('timestamptz', $column);
    }

}
  1. Create CustomPgsqlGrammar.php.

CustomPgsqlGrammar.php:

namespace App\Custom;

use Illuminate\Support\Fluent;
use Illuminate\Database\Schema\Grammars\PostgresGrammar;

class CustomPgsqlGrammar extends PostgresGrammar {

    protected function typeTimestamptz(Fluent $column)
    {
        return 'timestamp(0) with time zone';
    }

}
  1. In your migration file:

Don't forgot for

use App\Custom\CustomBlueprint;
use App\Custom\CustomPgsqlGrammar;
use Illuminate\Database\Migrations\Migration;

And then add code below before

Schema::create

DB::connection()->setSchemaGrammar(new CustomPgsqlGrammar());
$schema = DB::connection()->getSchemaBuilder();

$schema->blueprintResolver(function($table, $callback) {
    return new CustomBlueprint($table, $callback);
});
  1. How to use:

    $schema->create('users', function(CustomBlueprint $table) {

    $table->timestampz('completing_registration');
    

    }