Seed a pivot table using factories in Laravel
I do not think that this is the best approach but it works for me.
$factory->define(App\UserSkill::class, function (Faker\Generator $faker) {
return [
'user_id' => factory(App\User::class)->create()->id,
'skill_id' => factory(App\Skill::class)->create()->id,
];
});
If you do not want to create a model just for the pivot table, you can insert it manually.
DB::table('user_skill')->insert(
[
'user_id' => factory(App\User::class)->create()->id,
'skill_id' => factory(App\Skill::class)->create()->id,
]
);
Or, with random existing values.
DB::table('user_skill')->insert(
[
'user_id' => User::select('id')->orderByRaw("RAND()")->first()->id,
'skill_id' => Skill::select('id')->orderByRaw("RAND()")->first()->id,
]
);
For those who are using laravel 8.x and are looking for a solution to a problem like this;
In laravel 8.x you can feed your pivot using Magic Methods, For example if you have a belongsToMany relation named "userSkills" in User model, you should feed the pivot table this way:
User::factory()->hasUserSkills(1, ['skills' => 'draw'])->create();
You can find the documentation here
I had a similar problem and I resolved this way on Laravel testing.
Don't need to create a new UserSkills Model:
Version Laravel 5.7
Database
users user_skill skills
+----------------+ +------------------------------------+ +-----------------+
| id | name | | user_id | section_id | state_skill | | id | skills |
+----------------+ +------------------------------------+ +-----------------+
| 1 | Alex | | | | | | 1 | draw |
|----------------| |----------------------|-------------| |-----------------|
| 2 | Lucy | | | | | | 2 | program |
|----------------| |----------------------|-------------| |-----------------|
| 3 | Max | | | | | | 3 | social |
|----------------| |----------------------|-------------| +-----------------+
| 4 | Sam | | | | |
+----------------+ +----------------------+-------------+
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes;
public function skills()
{
return $this->belongsToMany('App\Skill')
->withTimestamps()
->withPivot('state_skill');
}
}
DataBaseTest.php
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
class DataBaseTest extends TestCase
{
/**
* @test
*/
public function test_create_user_skill()
{
// Create DataBase
$users = factory(\App\User::class, 1)
->create()
->each(function ($user) {
// Create Models Support
$skill = factory(\App\Skill::class)->create();
// Create Pivot with Parameters
$user->skills()->attach($skill->id,[
'state_skill' => 'ok'
]);
});
// Testing
// ...
$this->assertTrue(true);
}
}