Why "relationship" in my seeder code isn't working? It inserts to User model without any problem. But doesn't insert anything to UserMeta model. There is not even any error.
I have tested this code in controller. It was functioning fine with "relationship"
<?php
use Illuminate\Database\Seeder;
use App\User;
use App\UserMeta;
class MyUsersTableSeeder extends Seeder
{
/**
* Auto generated seed file.
*
* @return void
*/
public function run()
{
if (User::count() == 0) {
$user = User::create([
'name' => 'Admin',
'email' => '[email protected]',
'password' => bcrypt('password'),
'remember_token' => str_random(60),
]);
$user_meta = new UserMeta([
'meta_key' => 'role',
'meta_value' => 'admin',
]);
$user->UserMeta()->save($user_meta);
}
}
}
Model User
public function UserMeta()
{
return $this->hasOne('App\UserMeta', 'user_id');
}
Model UserMeta
public function user()
{
return $this->belongsTo('App\User');
}
users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
usermeta table
Schema::create('usermeta', function (Blueprint $table) {
$table->increments('user_meta_id');
$table->integer('user_id')->unsigned();
$table->string('meta_key');
$table->string('meta_value');
});
Change your
usermeta
migration toand re-run your migrations.