Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

You just did it, seriously ;) Have you tried your code? Note that the above method will only work for User object instance

There are also some helper methods in Eloquent, called mutators and accessors which you may also check:

http://laravel.com/docs/eloquent#accessors-and-mutators

If you wanted to transform your method to accessor you would rename it to getHappinessAttribute() and then your User will have a dynamic property which will return random number.


$user = new User();
// accessor
var_dump($user->happiness); // dumps random 1-100

Last updated 2 years ago.
0

Ya, I've tested it but always get the same error: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

Last updated 2 years ago.
0

Can you post your model and then the code you use to call the function?

Last updated 2 years ago.
0

It's probably because you're doing sth like

echo $user->happiness // without parentheses

instead of

echo $user->happiness() // with parentheses

There is significant difference between these two pieces of code.

The first one checks if user has happiness field in DB first, if he hasn't then Eloquent automatically calls happiness() method which as the exception says should return relation (one-to-many, many-to-many, etc). Since we're returning simple number this exception will be raised.

But if you want to access the method explicitly, use the second code - with parentheses $user->happiness() this way you call the method directly without involving Eloquent relation lookup.

Last updated 2 years ago.
0

Ahh, okay! Added the parentheses, now it works. Thanks a lot! :)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

nehalist nehalist Joined 24 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.