Laravel seeder : Call to undefined method IlluminateNotificationsNotification::getConnectionName()

  factory, laravel, php

i have a many-to-many relationship between two models

User

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use IlluminateNotificationsNotification;
use IlluminateSupportFacadesHash;
use LaravelPassportHasApiTokens;

class User extends Model
{
    use HasApiTokens, Notifiable,hasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email', 'password', 'first_name', 'last_name', 'username', 'phone',
        'address_id', 'c_gender_id'
    ];

    public function notifications()
    {
        return $this->belongsToMany(Notification::class);
    }
}

Notification

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
 
class Notification extends Model
{
    /**
     * @var array
     */
    protected $guarded = ['id'];
    use HasFactory;
    /**
     * @return IlluminateDatabaseEloquentRelationsBelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

i created a factory for each model User and Notification and a Seeder which calls the two factories in order to create users and attach to each one of them notifications

NotificationUserSeeder

    public function run()
    {
        User::factory()->times(2)->create();
        Notification::factory()->times(2)->create();
        $notifications = Notification::all();

        User::all()->each(function ($user) use ($notifications) {
            $user->notifications()->attach(
                $notifications->random(rand(1, 3))->pluck('id')->toArray()
            );
        });
    }

when running db:seed am getting this error :

Call to undefined method IlluminateNotificationsNotification::getConnectionName()
and apparently it’s caused from the User model

Source: Ask PHP

LEAVE A COMMENT