ID column in PostgreSQL (Laravel 5.8)

Posted 2 months ago by mleontenko

I'm creating a laravel application that lets users make a blog post.

The Post model looks like this:


namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Table Name
    protected $table = 'posts';
    // Primary key
    public $primaryKey = 'id';
    // Timestamps
    public $timestamps = true;
}

And this is the migration file:


use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id')->generatedAs()->always();
            $table->string('title');
            $table->mediumText('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}```

I'm using a PostgreSQL database and the problem is that $table->increments('id'); makes the ID column "Integer" type instead of "Serial" which is used in Postgres for this type of field.

This creates the following error when I try to update posts:
```Unique violation: 7 ERROR: duplicate key value violates unique constraint "posts_pkey" DETAIL: Key (id)=(1) already exists. (SQL: insert into "posts" ("title", "body", "updated_at", "created_at") values (Post 3, Test test test, 2019-03-06 17:27:37, 2019-03-06 17:27:37) returning "id")```

I need a way to define this field as "serial".

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.