Laravel Nova在表单上手动设置ID

时间:2018-12-03 14:46:10

标签: id laravel-nova

我想手动设置我的ID 因为我的ID类型为字符串(varchar)

这是我的模特

<?php

namespace App\Model\Master;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class UnitOfMeasure extends Model 
{

protected $table = 'unit_of_measures';
public $timestamps = true;
public $incrementing = false;

use SoftDeletes;

protected $dates = ['deleted_at'];
protected $fillable = array('id','code', 'description', 'scan_input_required');

public function workCenter()
{
    return $this->hasMany(WorkCenter::class,'unit_of_measures_code','code');
}

但是Nova总是隐藏ID字段。 有办法吗?

谢谢

2 个答案:

答案 0 :(得分:1)

如果查看调用creation-fields端点的请求,您会发现ID甚至不在字段列表中。

您的资源使用的特征ResolvesFields正在调用函数creationFields来生成要显示在前面的字段列表,这将调用 removeNonCreationFields

/**
 * Remove non-creation fields from the given collection.
 *
 * @param  \Illuminate\Support\Collection  $fields
 * @return \Illuminate\Support\Collection
 */
protected function removeNonCreationFields(Collection $fields)
{
    return $fields->reject(function ($field) {
        return $field instanceof ListableField ||
               $field instanceof ResourceToolElement ||
               $field->attribute === $this->resource->getKeyName() ||
               $field->attribute === 'ComputedField' ||
               ! $field->showOnCreation;
    });
}

并且由于该字段符合以下规则:

$field->attribute === $this->resource->getKeyName()

ID字段将被删除。

要强制使用该字段,您可以在资源中覆盖该函数:

/**
 * Remove non-creation fields from the given collection.
 *
 * @param  \Illuminate\Support\Collection  $fields
 * @return \Illuminate\Support\Collection
 */
protected function removeNonCreationFields(Collection $fields)
{
    return $fields->reject(function ($field) {
        return $field instanceof ListableField ||
               $field instanceof ResourceToolElement ||
               $field->attribute === 'ComputedField' ||
               ! $field->showOnCreation;
    });
}

答案 1 :(得分:0)

我自己遇到了这个问题,看来Nova已更新,因此您只需将ID字段手动添加到资源Text::make('ID')中,然后您将拥有一个可编辑的ID字段。

这是github问题:https://github.com/laravel/nova-issues/issues/268