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

jufrensius's avatar

How to store user id and 2 foreign key ids into pivot table after user create new user?

Helo,

I have a pivot table with 3 foreign key ids related to 3 tables. In userController@store, I want to store user_id, business_unit_id, and division_id in the pivot table. So when the admin submits in create user form, the controller will create a new user in the user table and store those ids into the pivot table. But I'm a little bit confused with the error, like

SQLSTATE[HY000]: General error: 1364 Field 'division_id' doesn't have a default value (SQL: insert into `business_unit_division_user` (`business_unit_id`, `user_id`) values (12, 1)) 

or

Array to string conversion

Below is the migration, model, validation and controller.

Migration

Schema::create('business_unit_division_user', function (Blueprint $table) {
            $table->foreignId('business_unit_id')
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->foreignId('division_id')
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->foreignId('user_id')
                ->constrained()
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->unique(['business_unit_id', 'division_id', 'user_id'], 'business_unit_division_user');

App\Models\User.php

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable, HasApiTokens, HasRoles, SoftDeletes, LogsActivity;

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'employee_id', 'name', 'email', 'password', 'status',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = bcrypt($password);
    }

    public function business_units()
    {
        return $this->belongsToMany(BusinessUnit::class, 'business_unit_division_user', 'business_unit_id', 'user_id');
    }

    public function divisions()
    {
        return $this->belongsToMany(Division::class, 'business_unit_division_user', 'division_id', 'user_id');
    }
}

App\Models\BusinessUnit.php

class BusinessUnit extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['name'];

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $date = ['deleted_at'];

    public function divisions()
    {
        return $this->hasMany(Division::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'business_unit_division_user', 'user_id', 'business_unit_id');
    }

    public static function boot()
    {
        parent::boot();

        self::deleting(function ($bu) {
            $bu->divisions()->each(function ($division) {
                $division->delete();
            });
        });
    }
}

App\Models\Division.php

class Division extends Model
{
    protected $guarded = [];

    public static function boot()
    {
        parent::boot();

        self::deleting(function ($division) {
            $division->departments()->each(function ($department) {
                $department->delete();
            });
        });
    }

    /**
     * the table has relationship to another tables
     *
     * @var array
     */

    public function business_unit()
    {
        //
        return $this->belongsTo(BusinessUnit::class);
    }

    public function departments()
    {
        return $this->hasMany(Department::class);
    }

    public function users()
    {
        return $this->belongsToMany(User::class, 'business_unit_division_user', 'user_id', 'division_id');
    }
}

Pivot Model App\Models\BusinessUnitDivisionUser.php

class BusinessUnitDivisionUser extends Pivot
{
    use HasFactory;

    protected $table = 'business_unit_division_user';
    protected $fillable = ['business_unit_id', 'division_id', 'user_id'];
}

app\Http\Requests\StoreUserRequest.php

public function rules(): array
    {
        return [
            'employee_id' => 'required',
            'name' => 'required|string',
            'email' => 'required|email:rfc,dns|unique:users,email',
            'password' => 'required',
            'status' => 'required',
            'role' => 'required',
            'notify' => 'required',
            'business_unit_id.*' => 'required',
            'division_id.*' => 'required',
        ];
    }

app\Http\Controllers\Admin\UserController.php

public function store(StoreUserRequest $request): mixed
    {
        $validated = $request->validated();
        $user = User::create($validated);
        $user->assignRole($request->input('role'));
        $user->business_units()->attach($request->business_unit_id, ['division_id' => $request->division_id]);

        if ($request->notify == 1) {
            Mail::to($request->email)->send(new NewUserNotification(
                $request->employee_id,
                $request->name,
                $request->email,
                $request->password,
                $request->role,
            ));
        }

        return redirect()->route('admin.user.index')->with('success', __('alert.store'));
    }
0 likes
1 reply
aosdev's avatar

I found an example from my older projects, maybe this works for you too;

->syncWithPivotValues($order_id, ['payment_id' => $payment->id])

Please or to participate in this conversation.