Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

abkrim's avatar
Level 13

Seed with factory in One to Many with pivot table

Hi there. I think I am not understanding something with Eloquent, and this makes me unable to understand how to create an adequate factory to do a minimum seeding for the app.

Scene

  • A campaign has more than one subscriber
  • A user can be in more than one campaign

Relations DB

I understand that it is a one-to-many relationship with a pivot table.

Tables

campaing

$table->id();
$table->string('name',100)->nullable(false)->unique();
$table->string('db',100)->nullable(false);
$table->string('table',100)->default('users')->nullable(false);
$table->timestamps();

campaing_subscribers

$table->unsignedBigInteger('campaing_id');
$table->foreign('campaing_id')->references('id')->on('campaings');

$table->unsignedBigInteger('subscriber_id');
$table->foreign('subscriber_id')->references('id')->on('subscribers');

$table->primary(['campaing_id','subscriber_id']);

$table->timestamps();

susbcribers

$table->id();
$table->string('email')->unique();
$table->timestamps();

Models

Campaing

protected $fillable = ['name', 'db', 'table'];

public function subscribers()
{
    return $this->belongsToMany(Subscriber::class, 'campaing_subscribers');
}

Subscriber

protected $fillable = ['email'];

public function campaing()
{
  return $this->belongsTo(Campaing::class);
}

Campaing_susbcribers

protected $fillable = ['campaings_id', 'subscribers_id'];

Factories

CampaingFactory

    {
        $campaing = $this->faker->company();
        $db = Str::slug($campaing, '_');
        return [
            'name' => $campaing,
            'db' => $db
        ];
    }

SusbcriberFactory

public function definition()
    {
        return [
            'email' => $this->faker->unique()->safeEmail(),
        ];
    }
0 likes
3 replies
SilenceBringer's avatar

@abkrim also your relationship in subscribers must be belongsToMany, not belongsTo

public function campaing()
{
  return $this->belongsToMany(Campaing::class);
}

and - you do not need separated model for Campaing_susbcribers

1 like
abkrim's avatar
Level 13

A lot of thanks, @s4muel and @silencebringer One, for warn of typo (I have had to correct my standard error in classes, migrants, models ... a real mistake with my English) Ohter for mistake in belongsToMany mistake.

Please or to participate in this conversation.