2

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' => 'authuser@auth.com',
            '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');
}
mrmar
  • 1,407
  • 3
  • 11
  • 26

3 Answers3

1

In your user creation method

Instead of

'gender_id' => $genders->random(),

you can use this

'gender_id' => rand(1,3),
Inzamam Idrees
  • 1,955
  • 14
  • 28
1

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!

mare96
  • 3,749
  • 1
  • 16
  • 28
  • you don't need to pull all the records if you are just going to pluck a single column, just call `pluck` on the Builder: `$ids = Gender::pluck('id')` and you dont need to convert the Collection to an array, Collections have a `random` method: `$ids->random()` – lagbox Dec 18 '19 at 12:49
0

No need to add genders here.You can do that in other seeder or manually do that.Here in your genders id should be in 1,2 & 3 .fixed.THen you can use rand() function here.rand() is a php function .rand() define a random number & you can fixed it value like rand(min,max) so just here use this rand(1,3)

public function run()
    {

    $genders = DB::table('genders')->insert([
            [
                'genders' => 'Woman',
            ],
            [
                'genders' => 'Woman Looking For Woman',
            ],
            [
                'genders' => 'Man',
            ]
        ]);//your wish to seed this gender in here

        DB::table('users')->insert([
            'gender_id' => rand(1,3),
            'name' => 'authuser',
            'email' => 'authuser@auth.com',
            'email_verified_at' => now(),
            'password' => Hash::make('auth123456'),
            'age' => 18,
            'remember_token' => Str::random(10), 
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]); 
    }
albus_severus
  • 3,626
  • 1
  • 13
  • 25