ubaid
3 years ago

Error Eloquent relationship when used as method

Posted 3 years ago by ubaid

Hi, I am trying to understand relationships in Laravel, When I use the relationship name as a property it works fine, but when I change it to a method so I can get a collection it gives me a 500 Internal Server error. Please see the following code, I am connecting UserType and SiteLocation with a hasMany relationship.

class UserType extends Model {
public function siteLocations()
    {
        return $this->hasMany('App\SiteLocation', 'user_type_fk');
    }
}
class SiteLocation extends Model {
public function userType()
    {
        return $this->belongsTo('App\UserType', 'user_type_fk');
    }
}
// I want to create a record
$userType = UserType::where(...); // I get this user correctly
$userType->siteLocations(); // 500 internal error
$userType->siteLocations; // works fine.

Please sign in or create an account to participate in this conversation.