lundi 25 mars 2019

How to attach a relationship to a Factory generated object in Laravel

This has been asked a few times but it seems most of the answer bodge something together in the seeder to achieve this OR create roles using a factory however I want to use ones already in the database.

I'm using the Laravel afterCreation method to try and sync the selected role to the newly created user like so:

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'email_verified_at' => now(),
        'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
        'remember_token' => Str::random(10),
    ];
});

$factory->afterCreating(App\User::class, function ($user, $faker) {

    $roles = Role::where('name', 'user')->get();
    $user->roles()->sync($roles->pluck('id')->toArray());

});

In my controller this code works, however, in the Factory I get the following warning when trying to create them with tinker:

PHP Warning: Illegal offset type in /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php on line 139

The users are being created but the selected role is not being 'synced' like expected.

Where am I going wrong here? Bearing in mind I don't want to create random roles in another factory.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire