pierluromani
pierluromani

Reputation: 57

Null value passed with select2 field type

My Product model has a code foreign key which points to a Code model, which also has a code coulmn but as a primary key. In the Create view of Product's CRUD, I created a dropdown field that allows me to choose from all the already existing Codes using the Select2 field type.

[
    'label'     => 'Code',
    'type'      => 'select2',
    'name'      => 'code',             // the foreign key
    'entity'    => 'productCode',      // the relationship's method
    'model'     => 'App\Models\Code', 
    'attribute' => 'code',             // attribute that is shown in the dropdown
]

The codes are shown correctly in the dropdown, but when I save the new product the code field is stored in the request as a null value. Anyone knows what the issue could be? Or if I'm getting some of this wrong?

This is the relationship in the Product model:

public function productCode() {
    return $this->belongsTo('App\Models\Code', 'code', 'code');
}

Upvotes: 0

Views: 270

Answers (1)

Wesley Smith
Wesley Smith

Reputation: 19571

A primaryKey property is required on a model when your primary key is not the typical "id" column, and keyType property is required if that primary key is not an integer column:

Adding the below to your App\Models\Code model should fix the problem:

/**
 * The primary key for the model.
 *
 * @var  string
 */
 protected $primaryKey = 'code';


/**
 * The "type" of the primary key
 *
 * @var  string
 */
protected $keyType = 'string';

Upvotes: 2

Related Questions