Search code examples
phplaravellaravel-seeding

Problem with seeding users to database in Laravel


I am trying to seed users in database but I get error saying

Symfony\Component\Debug\Exception\FatalThrowableError  : Call to a member function random() on bool

I have users table and genders table with gender_id in users table that points to Man or Woman column in genders table with hasMany relationship. I want to be able to write gender_id automatically in users table when I seed the database and create a new user. Currently with this code I get that error from above and NULL in gender_id column, but rest it inserts correctly in both users and genders table. When I remove random() function then it inserts always 1 in gender_id, but I want to be able to write 1 or 2 randomly. Also when I dump $genders it returns TRUE. Is there some way around this, any help is appreciated. Here is my code.

UserSeeder.php

<?php

use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UsersTableSeeder extends Seeder
{
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
        $genders = DB::table('genders')->insert([
            [
                'genders' => 'Woman',
            ],
            [
                'genders' => 'Woman Looking For Woman',
            ],
            [
                'genders' => 'Man',
            ]
        ]);

        //dd($genders);

        DB::table('users')->insert([
            'gender_id' => $genders->random(),
            'name' => 'authuser',
            'email' => '[email protected]',
            'email_verified_at' => now(),
            'password' => Hash::make('auth123456'),
            'age' => 18,
            'remember_token' => Str::random(10), 
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]); 
    }
}

users table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('gender_id')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->default();
            $table->integer('age')->default()->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

genders table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGendersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('genders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('genders');
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('genders');
    }
}

User.php

public function gender()
{
    return $this->belongsTo(Gender::class, 'gender_id', 'id');
}

Gender.php

public function users()
{
    return $this->hasMany(User::class, 'gender_id', 'id');
}

Solution

  • You can pluck your id values from Gendre and do randomly on that like this:

    $genders = DB::table('genders')->insert([
                ['genders' => 'Woman'],
                ['genders' => 'Woman Looking For Woman'],
                ['genders' => 'Man']
            ]);
    $gendreIds = Genders::pluck('id');
    
    DB::table('users')->insert([
                'gender_id' => $gendreIds->random(),
                ...
    ]); 
    

    This will give you gender which exists in database.

    Sometimes seed wouldn't give you id's from 1 to 3.

    So I think it's not best solution to use rand(1,3).

    Good luck!