salep
salep

Reputation: 1390

Laravel 5.1 : Migrate existing database

https://github.com/Xethron/migrations-generator

I migrated my database structure into Laravel using php artisan migrate:generate command with the help of the extension above. But there's a small problem, my primary key's aren't named as id, I rather used a different convention by adding a prefix for each of them like user_id, product_id, photo_id, etc. All of these are auto incremented, of course.

Here's my current create_users_table.php file inside my migrations folder. I defined user_id to override the default id option, is that the correct use?

<?php

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

class CreateUsersTable extends Migration
{

/**
 * Run the migrations.
 *
 * @return void
 */
    public function up()
{
    Schema::create('users', function (Blueprint $table) {
          $table->primary('user_id');
          $table->integer('user_id', true);
          $table->string('name', 500);
          $table->string('email', 500);
          $table->string('password', 500);
      }
    );
}


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

I read that I need to add something like below, but I'm not sure where to define protected $primaryKey since my class extends Migration rather than Eloquent.

class CreateUsersTable extends Eloquent {

    protected $primaryKey = 'user_id';

}

I'm getting the following error when I go to /auth/login page, which I think causes because of the user_id usage rather than id. How can I fix it?

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from `users` where `users`.`id` = 5 limit 1)

Upvotes: 7

Views: 3674

Answers (1)

Ben Claar
Ben Claar

Reputation: 3415

You need to specify your non-default primary key in your User model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {

    protected $primaryKey = 'user_id';

You will need to do this for all Models that don't use id as their primary key.

Upvotes: 3

Related Questions