Posts Learn Components Snippets Categories Tags Tools About
/

Laravel Livewire groupBy and Method getKey does not exist?

Learn how to fix grouping column issue in Laravel Livewire by using clean and straight forward method

Created on Jul 19, 2021

1578 views

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

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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)