0

I have a UserProfile model with associated table 'user_profiles' that has some fields like 'name', 'user_id', 'contact'. In the model there is a function which retrieves this data with the Eloquent ORM and adds an additional property 'provinces' to it before returning the profile object.

class UserProfile extends Eloquent {
    //....preceding methods ommitted
    public function totalProfile($userid) {
        $profile = $this->find($userid);
        $profile->provinces = Province::all();
        return $profile;
    }
}

When I call the above function from my UserProfilesController it returns the profile with no problem, but when I try to call the method from my PagesController it just returns empty, like so:

class PagesController extends \BaseController {
    public function __contstruct(UserProfile $userProfile) {
        $this->userProfile = $userProfile;
    }
    public function show($id) {
        print_r($this->userProfile->totalProfile($id)); //prints nothing
        die;
    }
}

I would really appreciate it if someone could help explain why this is? Thank you very much!

bryant
  • 2,041
  • 3
  • 18
  • 26
  • Would have to see the whole code. Do you have the correct use statement? What is in this->userProfile? – Benubird Aug 07 '18 at 11:50

1 Answers1

1

I'm not sure why you think this belongs on your model, but if you do, use this:

Model:

class UserProfile extends Eloquent {

    protected $appends = ['provinces'];

    public function getProvincesAttribute()
    {
        return Province::all();
    }

}

Controller:

class PagesController extends \BaseController {

    public function __contstruct(UserProfile $userProfile)
    {
        $this->userProfile = $userProfile;
    }

    public function show($id)
    {
        return Response::json($this->userProfile->find($id));
    }
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Thanks for your suggestion, I didn't know that about appending accessors to the model. Upon reading your post, I found [this additional post on the subject](http://stackoverflow.com/questions/17232714/add-a-custom-attribute-to-a-laravel-eloquent-model-on-load). – bryant Sep 09 '14 at 00:13
  • I see what you mean about adding this to the model, actually I don't want to add it, I just want to attach the data to it so I can return the provinces to the view in the same object for convenience since the model contains the district not the province, and I want to show province as well and will rethink this. But I think my problem is elsewhere, because there seems to be a problem even before I add the provinces. Maybe it has something to do with using $this->find($id) in the method, if I am accessing it from another controller? – bryant Sep 09 '14 at 00:17