jeudi 24 septembre 2015

Laravel 5.1 Eloquent relation Eager loading not working

I tried all the answers already on the forum, none helped me.

App\User.php Model defines hasOne relationship

public function apikey()
{
    return $this->hasOne('App\ApiKey', 'user_id', 'user_id');
}

App\ApiKey.php Model defines reverse relationship

protected function user()
{
    return $this->belongsTo('App\User','user_id','user_id');
}

Now I have a transform function with is call from controller return $this->response->withItem(**$users**, new UserTransformer);

App\Transformer\UserTransformer.php

public function transform($resource) //$resource is a users object
{
    $user_id = (int) $resource->user_id;
    $apiKey = $resource->apikey->key;
    return [
        'user_id' => $user_id,
        'apikey' => $apiKey
    ];
}

I get following error at $apiKey = $resource->apikey->key;

Trying to get property of non-object

I do not understand where am I going wrong Please suggest.

Thanks,

K



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire