Posts Learn Snippets Categories Tags 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

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

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.