1

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'          => 'admin@admin.com',
                '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');
        });
Miri
  • 976
  • 1
  • 9
  • 15

2 Answers2

1

Try following code:

$user_meta = new UserMeta([
                'meta_key' => 'role','user_id'=>$user_id,
            ]);
$user_meta->user_id=$user->id;
$user_meta->save();
Margus Pala
  • 8,433
  • 8
  • 42
  • 52
1

Change your usermeta migration to

Schema::create('usermeta', function (Blueprint $table) {
    $table->increments('user_meta_id');
    $table->integer('user_id')->unsigned();

    // add foreign key constraint
    $table->foreign('user_id')->references('id')->on('users');

    $table->string('meta_key');
    $table->string('meta_value');
});

and re-run your migrations.

Sreejith BS
  • 1,183
  • 1
  • 9
  • 18