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

arthos's avatar

Error while trying to seed a new app

Hey all,

I'm out of ideas on how to debug my problem, I can't find what's wrong for the life of me. Any help, please? I am trying to seed my app but all I get is a Call to undefined method App\Models\User::set() when the AddressSeeder is running (I don't use the set() method anywhere, so it must be related to something else). Only package I use for now is spatie/laravel-permission, but I don't reckon that's what causing the problem (disabling that seeder doesn't change anything).

In overall, I'm trying to seed my app with users (with different roles : admin, subscriber and cooperator), attach at least one address to a user, then a cooperation to that address. I cannot fathom how to seed addresses and attach it to an already existing user.

App\Models\User.php :

<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Address;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'date_of_birth',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'date_of_birth' => 'datetime',
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    public function addresses(): HasMany
    {
        return $this->hasMany(Address::class);
    }
}

App\Models\Address.php

<?php

namespace App\Models;

use App\Models\User;
use App\Models\Cooperation;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Address extends Model
{
    use HasFactory;

    protected $fillable = [
        'label',
        'user_id',
        'representative',
        'company_name',
        'address',
        'address_2',
        'zipcode',
        'city',
        'country',
        'telephone',
        'mobile',
        'is_company',
        'siret',
        'number_of_employees',
        'year_croec',
        'year_crcc',
        'college',
        'tva_intracom',
        'cooperated_at',
        'subscribed_at',
    ];

    protected $casts = [
        'user_id' => User::class,
        'cooperated_at' => 'datetime',
        'subscribed_at' => 'datetime',
    ];

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

    public function cooperation(): HasOne
    {
        return $this->hasOne(Cooperation::class);
    }
}

database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Database\Seeders\UsersSeeder;
use Database\Seeders\AddressSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        $this->call([
            RolesAndPermissionsSeeder::class,
            UsersSeeder::class,
            AddressSeeder::class,
            CooperationSeeder::class,
        ]);
    }
}

database/seeders/RolesAndPermissionsSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Spatie\Permission\Models\Role;

class RolesAndPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Coop
        $groupCoop = [
            'cooperator-receipt', // reçu de coopération
            'refund-cooperation', // remboursement de coopération
            'access-events', // voir et s'abonner aux événements
        ];
        $this->createPermissions($groupCoop);

        // Adh
        $groupAdh = [
            'read-documentation', // accéder à la documentation
            'access-news', // accéder aux actualités
            'access-revue', // accéder à la revue
            'access-models', // accéder aux modèles
            'access-fiches', // accéder aux fiches
        ];
        $this->createPermissions($groupAdh);

        // Admin
        $groupAdmin = [
            'create-users', // créer des utilisateurs
            'edit-users', // modifier des utilisateurs
            'delete-users', // supprimer des utilisateurs
        ];
        $this->createPermissions($groupAdmin);

        $roleCooperateur = Role::updateOrCreate(['name' => 'Coopérateur']);
        $roleAdherent = Role::updateOrCreate(['name' => 'Adhérent']);
        $roleAdmin = Role::updateOrCreate(['name' => 'Administrateur']);

        $roleCooperateur->givePermissionTo($groupCoop);
        $roleAdherent->givePermissionTo($groupCoop, $groupAdh);
        $roleAdmin->givePermissionTo($groupCoop, $groupAdh, $groupAdmin);
    }

    public function createPermissions(array $permissions): void
    {
        foreach ($permissions as $permission) {
            Permission::updateOrCreate(['name' => $permission]);
        }
    }
}

database/seeders/UsersSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Address;
use App\Models\Cooperation;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class UsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Admin
        $admin = User::factory()->create([
            'first_name' => 'Admin',
            'last_name' => 'ECFS',
            'email' => '[email protected]',
        ]);

        // $admin->assignRole('Administrateur');

        // Adhérent
        $adherent = User::factory()->create([
            'first_name' => 'Adhérent',
            'last_name' => 'ECFS',
            'email' => '[email protected]',
        ]);

        // $adherent->assignRole('Adhérent');

        // Coopérateur
        $cooperateur = User::factory()->create([
            'first_name' => 'Coopérateur',
            'last_name' => 'ECFS',
            'email' => '[email protected]',
        ]);

        // $cooperateur->assignRole('Coopérateur');

        User::factory(20)->create()->each(function (User $user) {
            // $user->assignRole('Adhérent');
        });

        User::factory(20)->create()->each(function (User $user) {
            // $user->assignRole('Coopérateur');
        });
    }
}

database/seeders/AddressSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Address;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class AddressSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $users = User::all();

        foreach ($users as $user) {
            $address = Address::factory()->create([
                'user_id' => $user->id,
            ]);

            $user->addresses()->save($address);
        }
    }
}

database/migrations/XXX_create_users_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('first_name')->nullable();
            $table->string('last_name')->nullable();
            $table->datetime('date_of_birth')->nullable();
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};

database/migrations/XXX_create_addresses_table.php

<?php

use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('addresses', function (Blueprint $table) {
            $table->id();
            $table->string('label')->nullable();
            $table->foreignIdFor(User::class)->constrained()->cascadeOnDelete();
            $table->string('representative')->nullable();
            $table->string('company_name')->nullable();
            $table->string('address')->nullable();
            $table->string('address_2')->nullable();
            $table->string('zipcode')->nullable();
            $table->string('city')->nullable();
            $table->string('country')->nullable();
            $table->string('telephone')->nullable();
            $table->string('mobile')->nullable();
            $table->boolean('is_company')->nullable();
            $table->string('siret')->nullable();
            $table->integer('number_of_employees')->nullable();
            $table->string('year_croec')->nullable();
            $table->string('year_crcc')->nullable();
            $table->string('college')->nullable();
            $table->string('tva_intracom')->nullable();
            $table->timestamp('cooperated_at')->nullable();
            $table->timestamp('subscribed_at')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('addresses');
    }
};

database/migrations/XXX_create_cooperations_table.php

<?php

use App\Models\Address;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('cooperations', function (Blueprint $table) {
            $table->id();
            $table->foreignIdFor(Address::class)->constrained()->cascadeOnDelete();
            $table->string('cooperation_number')->nullable();
            $table->timestamps();
            $table->timestamp('validated_at')->nullable();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('cooperations');
    }
};

Any help is very welcome...

Thanks by advance

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

Based on the information provided, the error message Call to undefined method App\Models\User::set() suggests that somewhere in your code (not necessarily in the seeders you've shown), there is an attempt to call a set() method on a User model instance, which does not exist.

However, from the code you've provided, there is no direct call to a set() method. This could mean that the error is being triggered by some underlying functionality or a package that is trying to call this method. Since you mentioned that disabling the RolesAndPermissionsSeeder does not change anything, we can likely rule out the spatie/laravel-permission package as the direct cause.

Here are a few steps you can take to debug this issue:

  1. Check Model Factories: Ensure that your User and Address factories are not calling a set() method on the model instances.

  2. Trace the Error: If you're using an IDE or editor that supports Xdebug, set a breakpoint at the point where the error occurs and trace back the stack to find where the set() method is being called.

  3. Search the Codebase: Perform a global search across your entire codebase for ->set( to see if there are any direct calls to a set() method.

  4. Review Relationships: In your Address model, the $casts attribute is incorrectly casting the user_id to User::class. The $casts property should be used to cast attribute values to native types, not to other models. This should be removed as it might be causing unexpected behavior.

protected $casts = [
    // 'user_id' => User::class, // Remove this line
    'cooperated_at' => 'datetime',
    'subscribed_at' => 'datetime',
];
  1. Check Service Providers: Sometimes service providers can register functionality that might be causing the issue. Check any custom service providers you have created.

  2. Review Event Listeners: If you have any event listeners or observers for the User or Address models, ensure they are not calling a set() method.

  3. Check Middleware: If there is any middleware that interacts with the User model, ensure it's not calling a set() method.

  4. Review Package Service Providers: Although you've ruled out the spatie/laravel-permission package, it's still worth checking if any other package service providers are trying to call a set() method on the User model.

  5. Laravel Debugging Tools: Use Laravel's built-in debugging tools such as Log::debug() or dd() to output variable contents and trace the flow of execution to where the error occurs.

  6. Check Database Seeders: Ensure that the AddressSeeder is not calling a set() method indirectly through some other method or relationship.

If after all these steps you still can't find the source of the error, consider posting more details or the full stack trace of the error message to get more specific help.

arthos's avatar

@LaryAI

If anyone gets that error, that's because of the 4th point (the first one): my casts were wrong, and that triggered the issue.

Thanks to the IA :)

Please or to participate in this conversation.