Laravel: Seeding table with several belongs to relationship using factories
You have to use associate()
:
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->make()->each(function ($post) {
$post->user()->associate(User::inRandomOrder()->first());
$post->category()->associate(Category::inRandomOrder()->first());
$post->save();
});
}
Also User::all()->random(1)
will return a collection and not a model, which will throw an exception, I replaced it with Model::inRandomOrder()->first()
, which will fetch a random model from the database.
From the docs:
When updating a belongsTo relationship, you may use the associate
method. This method will set the foreign key on the child model:
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
Update
In your Modelfactory:
/** @var Factory $factory */
$factory->define(Post::class, function (Faker\Generator $faker) {
return [
// not sure why you do this, is it not a autoincrement column?
'id' => $faker->unique()->randomNumber(3),
'name' => $faker->realText($maxNbChars = 200, $indexSize = 2),
'category_id' => function () {
if ($category = Category::inRandomOrder()->first()) {
return $category->id;
}
return factory(Category::class)->create()->id;
},
'user_id' => function () {
if ($user = User::inRandomOrder()->first()) {
return $user->id;
}
return factory(User::class)->create()->id;
},
];
});
In your seeder:
public function seed()
{
factory(User::class, 10)->create();
factory(Category::class, 10)->create();
factory(Post::class, 100)->create();
}
Laravel 8: How to seed a pivot table in many to many relationship
so first you can check if in the database there is Atg
, if no you can seed like you do, otherwise you can seed Debtor
then save Atg
in relations(->atg()
is your relation name so improve it if i wrote wrong name) like so:
P.S. Also i removed ->count(1)
from Debtor
because by default it creates one item.
<?php
namespace Database\Seeders;
use App\Models\Atg;
use App\Models\Debtor;
use Illuminate\Database\Seeder;
class DebtorSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$atg = Atg::first();
if($atg){
$debitor = Debtor::factory()
->create();
$debitor->atg()->save($atg);
}else {
$debitor = Debtor::factory()
->hasAtg(1)
->create();
}
}
}
Seed data with relationship in Laravel
You can query which roles you want to assign to the companies and related them to the created records like this:
class CompanySeed extends Seeder
{
public function run()
{
$contractorRole = Role::whereName('Contractor')->firstOrFail();
$ownerRole = Role::whereName('Owner')->firstOrFail();
factory(Company::class, 10)->create()->each(function ($company) use ($contractorRole, $ownerRole) {
$company->roles()->attach([
$contractorRole->id,
$ownerRole->id
]);
});
}
}
You can check the doc for relating records https://laravel.com/docs/5.6/eloquent-relationships#inserting-and-updating-related-models
How to seed related data during migration in Laravel?
This is what worked for me:
App\Models\Client::factory(10)->create()->each(function ($client) {
$client->contract()->save(Contract::factory()->make());
});
Seeding Relationship one to many in Laravel
attach for many to many relationships, you don't need device_user table for one to many relationship, in one to many you should create a column with name user_id in device table and just it. after that you can insert data in device table with user_id. and get user relationship with
Device::user()->get();
Laravel Seed with Relationship (Real Data)
Your Car model:
public function brand()
{
return $this->belongsTo(\App\Brand::class, 'brand_id');
}
Your Brand model:
public function cars()
{
return $this->hasMany(\App\Car::class);
}
Your cars
migration:
public function up()
{
Schema::create('cars', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->enum('type_of_car', ['small', 'medium', 'large']); // just extra example
$table->year('year');
$table->mediumInteger('horse_power');
// car's brand id below
$table->unsignedInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands')->onDelete('cascade');
});
}
To seed your cars
table, you can insert any id
from brands
table into brand_id
in your cars
table, for example:
Car::create([
'name' => 'S4',
'type_of_car' => 'medium',
'year' => '2014',
'horse_power' => 333,
'brand_id' => 3 // <-- this id should exist in brands table
]);
If you are seeding cars with random brands, you can insert a random brand id instead of hardcoding the id (like I did above with brand_id being 3):
...
'brand_id' => \App\Brand::all('id')->random()->id
]);
Related Topics
How to Run the Bind_Param() Statement in PHP
Is MySQLi_Multi_Query Asynchronous
PHP String Doesn't Allow < and > Characters
Select MySQL Rows But Rows into Columns and Column into Rows
How to Get Value from Form Without Submitting It
PHP Using Declare? What Is a Tick
MySQL Group by and Fill Empty Rows
Group Duplicate Array Keys in a Multidimensional Array into Subarray
Passing Data via Modal Bootstrap and Getting PHP Variable
Do I Need to Escape Backslashes in PHP
Download of .Zip File Runs a Corrupted File PHP
How to Pass an Array of Pdo Parameters Yet Still Specify Their Types