Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 601
salep Avatar asked Aug 07 '15 21:08

salep


People also ask

How do I add a column in laravel migration without losing data?

database\migration\add_new_column_to_products_table.php Now you can run migrate command to add this new field. Simply you can run below command to auto add a new field. Hope it can help you. Laravel Migration example tutorial, in this tutorial you have learned how to add new column to a table without losing data.


1 Answers

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.

like image 92
Ben Claar Avatar answered Sep 20 '22 10:09

Ben Claar