Home / Snippets / Laravel Livewire groupBy and Method getKey does not exist?
Laravel Livewire groupBy and Method getKey does not exist? cover

Laravel Livewire groupBy and Method getKey does not exist?

1.6K

3 years ago

0 comments

You might have come across an error when grouping a column inside Laravel Livewire component saying "getKey" does not exist and although this error is a bit vague there's a simple fix to this.

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

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this