laravel livewire 显示常量表达式包含无效操作,如何修复此错误

laravel livewire showing Constant expression contains invalid operations, how to fix this error

显示常量表达式包含无效操作

我是 laravel livewire 的新手,当我试图传递函数值时它显示

Constant expression contains invalid operations.

我正在尝试这个功能

'suppliers_master_id'        => $this->generateRegistrationId(),

我的代码

<?php

namespace App\Http\Livewire\Purchase;

use App\Supplier;
use Livewire\Component;

class AddSuppliers extends Component
{

        public $form = [
        'supplier'          => '',
        'email'              => '',
        'phone'              => '',
        'address'            => '',
        'city'               => '',
        'state'              => '',
        'pincode'            => '',
        'GSTIN'              => '',

        'suppliers_master_id'        => $this->generateRegistrationId(),


    ];

    public function submit()
    {
        $this->validate([

            'form.supplier' => 'required|string|max:255',
            'form.email' => 'required|email',
            'form.phone' => 'required|string|max:10',
            'form.address' => 'required|string|max:255',
            'form.city' => 'required|string|max:255',
            'form.state' => 'required|string|max:255',
            'form.pincode' => 'required|string|max:6',
            'form.GSTIN' => 'required|string|max:255',


        ]); 


     Supplier::create($this->form);
     session()->flash('message', 'Supplier Added  successfully .');

     return redirect()->to('/addsuppliers');
    }


    function generateRegistrationId() {
    $id = 'SIIT_' . mt_rand(1000000000, 9999999999); // better than rand()

    // call the same function if the id exists already
    if ($this->registrationIdExists($id)) {
        return $this->generateRegistrationId();
    }

    // otherwise, it's valid and can be used
    return $id;
}

function registrationIdExists($id) {
    // query the database and return a boolean
    // for instance, it might look like this in Laravel
    return Supplier::where('suppliers_master_id', $id)->exists();
}

    public function render()
    {
        return view('livewire.purchase.add-suppliers');
    }


}

这不是 livewire 问题,在 PHP 中不允许调用函数来初始化 属性。

在常规 PHP 中,您可以在 __construct() 方法中分配它。

由于 Livewire 的工作方式有点不同,您必须改用 mount()

public function mount()
{
    $this->form['suppliers_master_id'] = $this->generateRegistrationId();
}