Laravel Livewire json 响应

Jec*_*che 2 php laravel laravel-livewire

我在使用 Livewire 将数据从 api 响应传递到组件刀片文件时遇到严重问题。起初,在我点击的那一刻,它加载得很好。下拉菜单会在下面引发错误。

Livewire 在尝试水合[注册]组件时遇到损坏的数据。确保 Livewire 组件的 [name, id, data] 在请求之间未被篡改。

我有一个正在加载职业的下拉列表,一开始加载得很好,但是当我从下拉列表中选择某些内容时,它会抛出该错误。

下面是我的组件代码

<?php

namespace App\Http\Livewire;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Livewire\Component;

class SignUp extends Component
{
    public $response = 0;
    public $data;
    //get all professions and their related prefixes
    public $professions;
    public $profession_id;
    public $prefix;

    public function mount()
    {
        $response = Http::get('http://localhost:8000/api/sign_up');
        $collection = json_decode($response);
        $this->professions = collect($collection->professions);
    }

    public function hydrate()
    {
        $response = Http::get('http://localhost:8000/api/sign_up');
        $collection = json_decode($response);
        $this->professions = collect($collection->professions);
    }


    public function render()
    {
        return view('livewire.sign-up', [
            'professions' => $this->professions
        ]);
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的组件刀片下拉列表

<div class="form-group">
   <select wire:model="profession_id" name="profession_id" class="form-control form-control-lg"
           id="exampleFormControlSelect2">
      <option value="">Choose Profession</option>
      @foreach($professions as $profession)
         <option value="{{$profession->id}}">{{$profession->description}}</option>
      @endforeach
   </select>
</div>
Run Code Online (Sandbox Code Playgroud)

Vin*_*des 5

询问和回答

您已经给出了有关您的问题的提示。

Livewire 组件的 [sign-up] 公共属性 [prefixes] 类型必须为:[数字、字符串、数组、null 或布尔值]。只有受保护或私有属性可以设置为其他类型,因为 JavaScript 不需要访问它们。

简答

变换collectionarray.

长答案

您可能只需要将集合转换为数组:

    public function mount()
    {
        $response = Http::get('http://localhost:8000/api/sign_up');
        $collection = json_decode($response);
        $this->professions = collect($collection->professions)->all();
    }
Run Code Online (Sandbox Code Playgroud)

更进一步,我注意到你只需要专业description人士id。所以你只需要返回:

    public function mount()
    {
        $response = Http::get('http://localhost:8000/api/sign_up');
        $collection = json_decode($response);
        $this->professions = collect($collection->professions)->pluck('description', 'id')->all();
    }
Run Code Online (Sandbox Code Playgroud)

当然,您需要相应地调整刀片:

@foreach($professions as $id => $desc)
   <option value="{{$id}}">{{$desc}}</option>
@endforeach
Run Code Online (Sandbox Code Playgroud)

请注意,我自己没有测试代码,所以也许您需要做一些调整。让我知道评论,以便我改进我的答案。