AJStacy AJStacy - 10 months ago 79
PHP Question

Eloquent Many to Many Attach Function sending a Null ID

I have the following code which is attempting to attach a product to a product_slot.

$product_slot = new ProductSlot;
$product_slot = $product_slot->where('type', $slot['id'])->first();

$product = new Product;
$product = $product->where('type', (String)$allowed_product)->first();


I can do a
and both return the following:

array (size=6)
'product_slot_id' => int 1
'type' => string 'breakfastplatter1' (length=17)
'default_product_id' => string 'bigbfhotcakebiscplat_3590' (length=25)
'allow_empty' => int 0
'created_at' => string '2016-08-17 19:04:41' (length=19)
'updated_at' => string '2016-08-17 19:04:41' (length=19)

array (size=7)
'product_id' => int 185
'type' => string 'bigbfhotcakebiscplat_3590' (length=25)
'label' => string 'Big Breakfast with Hot Cakes (Biscuit)' (length=38)
'min_option_slots' => int 0
'max_option_slots' => int 0
'created_at' => string '2016-08-17 19:05:40' (length=19)
'updated_at' => string '2016-08-17 19:05:40' (length=19)

Here is the Product Model relationship:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
protected $fillable = ['type', 'label', 'min_option_slots', 'max_option_slots'];

public function productSlots()
return $this->belongsToMany('App\ProductSlot');

However, when I try to sync these models together I get the following error.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'product_id' cannot be null (SQL: insert into

) values (, 1))

Ben Ben

You are using custom primary key names instead of the Laravel convention of using id as the primary key. Try adding this to your models:

class Product {
    public $primaryKey = 'product_id';

class ProductSlot {
    public $primaryKey = 'product_slot_id';

Also note that if you don't follow Laravel conventions, you also sometimes need to specify the non-standard primary keys when defining relationship functions:

public function productSlots()
    return $this->belongsToMany('App\ProductSlot', 'product_slot_id', 'product_id');