Andre
Andre

Reputation: 638

Can't paginate in livewire component

I'm trying to paginate items in a livewire component, I have this query

protected $listeners = [
  'franchises:coords' => 'getFranchises'
];

public $franchiseList;

public function render()
{
    return view('livewire.franchise-list', ['franchiseList' => $this->franchiseList]);
}

public function getFranchises($coords)
{
    if ($coords) {
        $latitude = json_decode($coords)[0];
        $longitude = json_decode($coords)[1];
        $radiusInMeters = 800;

        $this->franchiseList = Franchise::select(DB::raw('*, ( 6371000 * acos( cos( radians(' . $latitude . ') )
        * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(' . $longitude . ') )
        + sin( radians(' . $latitude . ') ) * sin( radians( latitude ) ) ) ) AS distance'))
            ->having('distance', '<', $radiusInMeters)
            ->orderBy('distance')
            ->paginate(8);
    }
}

the component is included in my "maps.blade"

            <div class="lg:basis-1/4 md:basis-1/4 sm:px-6 lg:px-8">
                <livewire:franchise-list/>
            </div>

and in my blade view, I have this

            @if(!empty($franchiseList))
                {{$franchiseList->links()}}
            @endif

but I get this error

Livewire component's [franchise-list] public property [franchiseList] must be of type: [numeric, string, array, null, or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't need to access them.

If I try to change pagination by adding these lines to the getFranchises function and adding $links to public

public $franchiseList, $links;

        //after paginate
        $this->links = $this->franchiseList;
        $this->franchiseList = collect($this->franchiseList->items);

and in the blade change to this

            @if(!empty($franchiseList) && $links->links())
                {{$links->links()}}
            @endif

I get this error

Error Cannot access protected property Illuminate\Pagination\LengthAwarePaginator::$items

How can I paginate in livewire? where is the problem?

Upvotes: 0

Views: 996

Answers (1)

Prospero
Prospero

Reputation: 2352

Ok, as I guess your issue is right there in render method. Instead of doing what you're doing, change this once you have in the mount the property initialized

public $franchiseList;

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

public function render()
{
    return view('livewire.franchise-list');
}

So, as the property is public you can bind it in blade directly. At load component, it is an empty array and on event (in listener) this will change to passed value. That's the idea, but if you do this ['franchiseList' => $this->franchiseList] it's going to be crashed (when same name). I can't tell you why because I really don't know the answer but I know this happens from my experience.

Upvotes: 0

Related Questions