Laravel: how to run seeder with relationships

742 views Asked by At

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');
        });
2

There are 2 answers

0
Sreejith BS On BEST ANSWER

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.

2
Margus Pala On

Try following code:

$user_meta = new UserMeta([
                'meta_key' => 'role','user_id'=>$user_id,
            ]);
$user_meta->user_id=$user->id;
$user_meta->save();