Reputation: 771
I'm creating a laravel application that lets users make a blog post.
The Post model looks like this:
<?php
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:
<?php
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');
$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".
EDIT: My PostsController store function looks like this:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
// Create post
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/posts')->with('success', 'Post created');
}
Upvotes: 1
Views: 3149
Reputation: 11461
By default, the 'id'
column is the primary key and you don't need to specify it in the model, maybe that's why it tries to make the column integer.
Try to remove the
public $primaryKey = 'id';
from the model definition and try to do a fresh migration and run the query.
I'm not sure about this answer but its a bit long for a comment so posting an answer
Upvotes: 1