Home > OS >  Laravel 9 Many to Many Pivot Table Creation Error "SQLSTATE[42S22]: Column not found: 1054 Unkn
Laravel 9 Many to Many Pivot Table Creation Error "SQLSTATE[42S22]: Column not found: 1054 Unkn

Time:07-13

I am trying to create a pivot table during the user registration, but I keep getting a SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' error and with the following message insert into 'location_user' ('location_id', 'user_id', '0', '1') values (3, 4, tenant_id, 3).

The code below works until the last line $location->users()->attach($user, ['tenant_id',$tenant->id]); and then I get the error.

location_user migration

...
public function up()
{
    Schema::create('location_user', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('tenant_id');
        $table->integer('location_id')->unsigned();
        $table->integer('user_id')->unsigned();
    });
}
...

RegisterUserController.php

...
public function store(Request $request){

$tenant = Tenant::create([
    'company_name' => $request->company_name,
    'postal_code' => $request->postal_code,
    'tenant_type' => $request->tenant_type,
]);

$location = Location::create([
    'name' => $request->name ? : 'Home',
    'tenant_id' => $tenant->id,
]);

$user = User::create([
    'first_name' => $request->first_name,
    'last_name' => $request->last_name,
    'email' => $request->email,
    'role' => 'primary',
    'toc' => $request->boolean('toc'),
    'password' => Hash::make($request->password),
    'tenant_id' => $tenant->id,
]);

$location->users()->attach($user, ['tenant_id',$tenant->id]);
...

Location.php

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

User.php

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

CodePudding user response:

There is a syntax error in RegisterUserController.php:

$location->users()->attach($user, ['tenant_id' => $tenant->id]);
  • Related