How to get data from laravel relationship in single object?

Viewed 441

IN USER MODEL this is my relation

public function User() {
    return $this->belongsTo('App\models\Users','UserId');
}

IN WALLET MODEL this is my relation

public function Wallet() {
    return $this->HasOne('App\Models\Wallet','UserId','Id');
}

but when i am running the query

    $user = Users::with([
        'Wallet' => function($query){
            $query->select('test_userwallet.UserId','test_userwallet.CoinBalance');
        }
    ])->get()->toArray();

i am getting the data in a object like this

{
    "Id": 1,
    "UID": "8oDI617ZlsInXtUkRpMqVKo5J4XPzI12567",
    "CountryCode": "91",
    "Status": "active",
    "TimeStamp": "2021-02-12 06:43:08",
    "wallet": {
        "UserId": 1,
        "CoinBalance": 6
    }

which is totally fine but i am guessing is there any way or method by which i can get the data in this format

{
    "Id": 1,
    "UID": "8oDI617ZlsInXtUkRpMqVKo5J4XPzI12567",
    "CountryCode": "91",
    "Status": "active",
    "TimeStamp": "2021-02-12 06:43:08",
    "UserId": 1,
    "CoinBalance": 6
    }

like in single object as i am working in apis so i want to do like that

note : only using query or eloquent

2 Answers

you can do this using join:

 $user = Users::query()->leftJoin('test_userwallet','test_userwallet.UserId','users.id')
            ->select(['test_userwallet.Id','UID','CountryCode','Status','TimeStamp','UserId','CoinBalance'])
       ->get()->toArray();

You've specified only using query or eloquent.

I would say the best way would be to return your endpoint response as a Resource from your controllers.

But if you must do it as a property on the model. You can use the $appends array and an accessor. See docs This will add the properties to the model any time it is serialised like when it's returned in a response.

protected $appends = [
    'coin_balance',
];

public function getCoinBalance Attribute()
{
    return $this->Wallet->coin_balance;
}
Related