0
votes

I want to seed the hero table, but I get the following error.

Argument 1 passed to Illuminate\Database\Query\Builder::insertGetId() must be of the type array, object given, called in

E:\xampp\htdocs\cyberpunk\vendor\laravel\framework\ src\Illuminate\Database\Eloquent\Builder.php on line 1350.

Exception trace: Illuminate\Database\Query\Builder::insertGetId(Object(App\Hero), "id") ...vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php:1350

Seeder

User::find(1)->hero()->create([
    'name' => $faker->userName,
    'level' => $faker->numberBetween(1, 99),
    'strength' => $faker->numberBetween(1, 20),
    'vitality' => $faker->numberBetween(1, 20),
    'stamina' => $faker->numberBetween(1, 20),
    'agility' => $faker->numberBetween(1, 20),
    'perception' => $faker->numberBetween(1, 20),
    'luck' => $faker->numberBetween(1, 20),
]);

I have a one-to-one relation between User and Hero. I want to create a new hero via the user model. This way also causes the same error.

$hero = new Hero;
$hero->user_id = 1;
...
$hero->save();

User

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public $appends = ['hashid'];

    public function hero()
    {
        return $this->hasOne(Hero::class);
    }
}

Hero Model

class Hero extends Model
{
    protected $fillable = ['level'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
1
Can you show us a Users and Heroes model classes?jureispro
Of course, i have edited post.daamian3
Can you post the entire Seeder fileAngad Dubey
try adding 'user_id' (and all others fields) to the fillable property in Hero Model : protected $fillable =[ 'user_id', 'level', ...];porloscerros Ψ

1 Answers

0
votes

The problem is your $fillable config. Try adding your fields to the $fillable:

class Hero extends Model {

    protected $fillable = ['level', 'client_id', ... ]; // <-- your allowed fields

    public function user() {
        return $this->belongsTo(User::class);
    }
}

Now, keep in mind that this will need to be applied for the majority of your fields. An alternative is to make use of the opposite, the $guarded attribute. You list there the fields that you want to protect against mass-assignment:

class Hero extends Model {

    protected $guarded = []; // <-- your protected fields go here

    public function user() {
        return $this->belongsTo(User::class);
    }
}

Check the related section of the documentation.