I am trying a one to many relationship between user and otp but i got a unknown column error. and i am using Sentinel for user auth.
Otp model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Sentinel;
class Otp extends Model
{
protected $fillable = ['user_id','phonenumber','otp'];
public function user()
{
return $this->belongsTo(Sentinel);
}
}
Sentinel user model.
namespace Cartalyst\Sentinel\Users;
........
.......
protected $table = 'users';
/**
* {@inheritDoc}
*/
protected $fillable = [
'username',
'password',
'permissions',
'relationship',
'status',
'phone'
];
public function otp()
{
return $this->hasMany('App\Otp');
}
.....
otp schema
Schema::create('otps', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('phonenumber');
$table->string('otp');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
});
sentinel user schema.
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('password');
$table->string('name')->nullable();
$table->bigInteger('phone')->nullable();
$table->integer('birth_month')->nullable();
$table->integer('birth_year')->nullable();
$table->integer('birth_day')->nullable();
$table->integer('relationship')->unsigned();
$table->integer('status')->nullable();
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('username');
});
so there i am accepting request from user which contains his phone number and i am trying to store it in otp table
public function phoneupdate(Request $request){
$this->validate($request, [
'phone' => 'bail|required|numeric|digits:10',
]);
$user = Sentinel::findById(3);
$randomOtp = rand (999 ,10000);
$user->otp()->create([
'phonenumber' => $request->phone,
'otp' => $randomOtp,
]);
return 'OK';
}
but gives an error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'eloquent_user_id' in 'field list'
(SQL: insert into `otps` (`phonenumber`, `otp`, `eloquent_user_id`, `updated_at`, `created_at`) values (1234567890, 5997, 3, 2016-12-23 11:34:55, 2016-12-23 11:34:55))
eloquent_user_id
is the problem it needs to be user_id
instead of eloquent_user_id
but as per laravel documentation it by default take the foreign key user_id
so why it is giving this error
and code works fine if i change
from
public function otp()
{
return $this->hasMany('App\Otp');
}
to
public function otp()
{
return $this->hasMany('App\Otp','user_id');
}
so why i need to define user_id
if it take by default from user_id
.