Laravel faker valid() 不应该被静态调用,但它不是

Laravel faker valid() should not be called staticlly, but it is not

我正在尝试使用Laravel中faker自带的valid()方法,如下:

<?php

namespace Database\Factories;

use App\Models\Attribute;
use App\Faker\AttributeValue as AttributeValueProvider;
use App\Models\Supplier;
use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\AttributeValue;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;


class AttributeValueFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = AttributeValue::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition(): array
    {
        $this->faker->addProvider(AttributeValueProvider::class);
        $attribute = Attribute::orderBy('id', 'desc')->first();
        $attribute_name = $attribute->translate('en')->name;
        $attribute_value = $this->faker->valid($this->is_valid_attribute_value($this, $attribute->id))->get_attribute_values($attribute_name);
        $supplier_id = Supplier::max('id');
        return [
            'en' => $attribute_value['en'] + ['supplier_id' => $supplier_id],
            'ar' => $attribute_value['ar'] + ['supplier_id' => $supplier_id],
        ];
    }

    public function is_valid_attribute_value($attribute_value, $attribute_id): bool
    {
        $valid = Validator::make(['attribute_value_translations' => $attribute_value], [
            'attribute_value' => [Rule::unique('attribute_value_translations', 'value')->where(function($q) use ($attribute_id){
                $q->where('locale', 'en')
                    ->where('attribute_id', $attribute_id);
            })]
        ])->passes();
        return $valid;
    }
}



但它抛出以下错误:

call_user_func_array(): Argument #1 ($callback) must be a valid callback, non-static method App\Faker\AttributeValue::valid() cannot be called statically

如你所见,我不是在静态调用它,请帮忙

如文档示例代码(以下摘录)中所述,Faker 需要回调作为 valid() 方法的参数。

$evenValidator = function($digit) {
    return $digit % 2 === 0;
};
for ($i = 0; $i < 10; $i++) {
    $values []= $faker->valid($evenValidator)->randomDigit;
}

但是您的代码将函数的 结果 传递给 valid() 方法,而不是函数本身。

$attribute_value = $this->faker
    ->valid($this->is_valid_attribute_value($this, $attribute->id))
//          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^  this is a boolean value, not a callback
    ->get_attribute_values($attribute_name);

要使用您的 class' 验证函数,您需要将其更改为

$attribute_value = $this->faker
    ->valid([$this, 'is_valid_attribute_value'])
    ->yourFakeProvidedValue;

后跟提供的假值。 Faker 然后会将提供的值传递给回调以检查其是否有效。