Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to a member function getKey() on string when collecting an array

Tags:

php

laravel

I'm trying to turn an associative array into a collection in order to merge it with another collection, but for some reason I'm getting the following error:

Call to a member function getKey() on string

My code:

$posts = Post::with(['category', 'user'])->get();

$toMerge = collect([ 'video' => '/img/misc/doggo.mp4', 'component' => 'slider-item-2' ]);

$mergedPosts = $posts->merge($toMerge);
like image 664
gabogabans Avatar asked May 04 '26 21:05

gabogabans


1 Answers

The problem is that $posts is a Illuminate\Database\Eloquent\Collection Object which override the merge method of the base base collection Illuminate\Support\Collection.

The merge method of Illuminate\Database\Eloquent\Collection expect another Illuminate\Database\Eloquent\Collection.

You need to reverse your merge:

$mergedPosts = $toMerge->merge($posts);
like image 109
alprnkeskekoglu Avatar answered May 06 '26 10:05

alprnkeskekoglu