0
votes

I'm trying to implements a 'has one' relation but this error prevent me to save the token.

Migrations :

class CreatePasswordTokensTable extends Migration
{
    public function up()
    {
        Schema::create('password_tokens', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('token');

        });
    }

    ...
}

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->engine = 'InnoDB';

            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password')->default('');
            $table->string('remember_token', 100)->default('');
            $table->boolean('active')->default(false);
            $table->timestamps();
        });
    }

    ...
}

Models :

class User extends Model
{
    public function passwordToken()
    {
        return $this->hasOne('App\Models\PasswordToken');
    }
}

class PasswordToken extends Model
{
    public function user() {
        return $this->belongsTo('App\Models\User');
    }
}

Commands - enter image description here

Strange user_id appear after the save call - enter image description here

Error :

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL: insert into users (email, id, user_id, updated_at, created_at) values (email, 1, 1, 2017-04-18 10:05:47, 2017-04-18 10:05:47))'

3

3 Answers

0
votes

If you are using Laravel 5.3 Try this :

Schema::create('password_tokens', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->unsignedInt('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->string('token');

        });
0
votes

I think you can update your model like this:

class User extends Model
{

   public function passwordToken(){
       return $this->hasOne('App\Models\PasswordToken','user_id', 'id');
   }

}

class PasswordToken extends Model
{

   public function user()
   {
       return $this->belongsTO('App\Models\User', 'user_id', 'id');
   }
}

Hope this work for you!

0
votes

Did you fill $table and $fillable attributes at your models?

Did you try the following?

$user->save();
$token->user_id = $user->id;
$token->save();