Danieloplata
5 months ago
115
4
Laravel

Pivot Table always returning null

Posted 5 months ago by Danieloplata

Here is my relationship..

Model - Group:

public function refreshments()
{
    return $this->belongsToMany(Refreshments::class, 'group_refreshments')
        ->withPivot('quantity');
}

Migration - create_refreshments_table:

Schema::create('refreshments', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name')->unique();
    $table->decimal('price');
    $table->timestamps();
});

Schema::create('group_refreshments', function (Blueprint $table) {
    $table->unsignedInteger('group_id');
    $table->unsignedInteger('refreshments_id');
    $table->tinyInteger('quantity');
    $table->primary(['group_id', 'refreshments_id']);
});

My tinker log:

php artisan tinker
Psy Shell v0.9.9 (PHP 7.1.20 — cli) by Justin Hileman
>>> $group = factory('App\Group')->create()
=> App\Group {#2969
     project_id: 2,
     start_time: "2019-05-30 10:36:36",
     end_time: "2019-05-30 10:36:36",
     participants: 13,
     participant_sandwiches: 1,
     clients: 16,
     client_sandwiches: 1,
     light_buffet: 0,
     hot_buffet: 0,
     cold_buffet: 1,
     takeaways: 1,
     hot_drinks_and_biscuits: 1,
     drinks: 1,
     food_timing: "ASAP",
     created_at: "2019-05-30 10:36:36",
     updated_at: "2019-05-30 10:36:36",
     id: 2,
   }
>>> $group->refreshments()->attach(1, ['quantity' => 5])
=> null
>>> $group->refreshments()->attach(14, ['quantity' => 10])
=> null
>>> $group->refreshments
=> Illuminate\Database\Eloquent\Collection {#2961
     all: [],
   }
>>> $group->refreshments()
=> Illuminate\Database\Eloquent\Relations\BelongsToMany {#2974
     +withTimestamps: false,
   }

The refreshments are successfully added and appear in my SQL client.

I suspect I may have an issue with the naming conventions (specifically Refreshments being plural?) which is why I tried to manually define the table name for the pivot.

Please sign in or create an account to participate in this conversation.