Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot merge on an Eloquent collection in Laravel

I need to merge either a collection or an array (it can be either) in Laravel 5.1, but I am getting the error BadMethodCallException in Builder.php line 2071: Call to undefined method Illuminate\Database\Query\Builder::merge()

When I make a collection from scratch, I can merge to it, but I cannot merge onto the result of an Eloquent query, which I thought were collections as well. But perhaps that is not true?

Code that gives the error:

$user=User::where('user_last_name', 'Doe')->first();
$tomerge = collect(['book' => 'desk', 'foot' => 'chair']);
$newcollect = $user->merge($tomerge);

If I instead did $tomerge->merge($user) it works, but that's not what I actually need. Is there a way to use merge as I want?

like image 716
llhilton Avatar asked Mar 14 '23 04:03

llhilton


1 Answers

To answer your question as to why it's not working...

$user = User::where('user_last_name', 'Doe')->first();

This is a single instance of a model. Not a collection. An eloquent model does not have the merge method.

If you want to append attributes to an Eloquent model, the simplest way is probably to use the $appends property and the appropriate accessor. For example, in your User model..

protected $appends = ['book', 'foot'];

public function getBookAttribute()
{
    return 'desk';
}
public function getFootAttribute()
{
    return 'chair';
}

However, note that this will affect every instance of your User model.

like image 120
Thomas Kim Avatar answered Apr 01 '23 17:04

Thomas Kim