Livewire Component
Imagine you have a "WorkSchedule" component and inside the "mount()" method you are querying a model that contains "groupBy" clause. With the code below you will see Livewire will throw an error "Illuminate\Database\Eloquent\Collection::getKey does not exist" because livewire doesn't support using "groupBy" on eloquent collections.
$this->schedule = WorkSchedule::query() ->get() ->groupBy('day');
The Fix
To fix the error above you can chain the existing query method with "toBase()" and that should fix it.
$this->schedule = WorkSchedule::query() ->get() ->groupBy('day') ->toBase();
Alternatively, you can make use of the computed property and you can define it like below.
public function getScheduleproperty() { return WorkSchedule::query() ->get() ->groupBy('day') ->toBase(); }
Full Code Example
The full code example should be like below and it's using the "toBase()" method to fix the error.
<?php namespace App\Http\Livewire; use App\Models\WorkSchedule; use Livewire\Component; class WorkSchedule extends Component { public $schedule; public function mount() { $this->schedule = WorkSchedule::query() ->get() ->groupBy('day') ->toBase(); } public function render() { return view('livewire.work-schedule'); } }
Leave a reply