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

时间:2020-06-07 07:48:30

标签: php laravel laravel-7 livewires laravel-livewire

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

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

常量表达式包含无效的操作。

正在尝试使用此功能

'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');
    }


}

1 个答案:

答案 0 :(得分:3)

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

在常规PHP中,您可以在YYYY-MM-DD hh:mm:ss方法中分配它。

由于Livewire的工作方式略有不同,因此您必须改用__construct()

mount()