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
Ya, I've tested it but always get the same error: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
Can you post your model and then the code you use to call the function?
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.
Ahh, okay! Added the parentheses, now it works. Thanks a lot! :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community