Guest012393
Guest012393

Reputation: 255

returning JSON response with multiple models

I am trying to return a JSON response which consists of an array of accounts where each account has one currency(name, rate).

what I got so far:

[
  {
    id: 10001,
    currency_id: 1,
    amount: 11000,
    currency: {
      id: 1,
      name: "Dollar",
      rate: 5.1
    }
  }
]

but what I need:

[
  {
    id: 10001,
    currency: {
      id: 1,
      name: "Dollar",
      rate: 5.1
    },
    amount: 11000,
  }
]

currency.php model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class currency extends Model {

    protected $fillable = array('name', 'rate');

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

account.php model:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class account extends Model {

    protected $fillable = array('client_id', 'currency_id', 'branch_id', 'credit', 'debit', 'type');

    public function currency()
    {
        return $this->belongsTo('App\currency');
    }
}

and my AccountController:

public function index()
    {
        $accounts = Account::with('currency')->get();

        return $accounts;
    }

Upvotes: 0

Views: 291

Answers (1)

Elie Fa&#235;s
Elie Fa&#235;s

Reputation: 3315

If you just want to hide currency_id you can use the $hidden property on your account model like so

protected $hidden = ['currency_id'];

See the doc here https://laravel.com/docs/5.1/eloquent-serialization#hiding-attributes-from-json

Upvotes: 1

Related Questions