【问题标题】:Laravel Livewire Save to Collection and Show in Component ViewLaravel Livewire 保存到集合并在组件视图中显示
【发布时间】:2021-04-22 21:50:55
【问题描述】:

我正在使用 Laravel Livewire 从下拉列表中选择一个项目(它传递一个 ID),然后找到该 ID 所属的模型,我想将该模型添加到集合中。然后每次我从下拉列表中选择一些东西时,我都想用那个新模型更新现有的集合。

public $workoutExercises;

public function mount()
{
  $this->workoutExercises = collect([]);
}

public function submitExercise()
{
  $newExercise = Exercise::where('id', $this->exercise)->first();

  $this->workoutExercises->push($newExercise);

  return;
}

在组件视图中:

@foreach ($workoutExercises as $workoutExercise)
  {{ $workoutExercise->exercise_name }}
@endforeach

当我提交一个新练习时,它会将其添加到集合中并按预期显示在我的视图中。然而,当我去添加一个额外的练习时,我得到了这个错误......“尝试读取数组上的属性“exercise_name”。

我不明白。就像它添加了第一个很好,但是对于任何后续提交都使用数组而不是集合?

TIA!

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    在后面,Livewire 使用了数组之类的所有东西,所以当组件第一次加载时,您的 $workoutExercises 是一个集合,但在第一次请求之后它变成了一个数组。我通常做的是创建一个选定的 id 数组并将数据作为计算属性查询。

    public array $workoutExerciseIds = [];
    
    public function submitExercise(): void
    {
      array_push($workoutExerciseIds, $this->exercise);
    }
    
    public function getWorkoutExecisesProperty()
    {
        return Exercise::query()
            ->whereIn('id', $this->workoutExerciseIds)
            ->get();
    }
    

    然后在我的前端:

    @foreach ($this->workoutExercises as $workoutExercise)
      {{ $workoutExercise->exercise_name }}
    @endforeach
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-10
      • 1970-01-01
      • 2018-04-04
      相关资源
      最近更新 更多