mardi 2 février 2016

Laravel simplify nested relation output

I get all items owned by authenticated user.

$items=Auth::user()->with('items')->get();

In my view i can access items collection, but instead of title_id want to retrieve item_title value. Currently i'm able to get item_title value using code below:

$item->title->title

Is it possible to simplify it to retrieve title like this: $item->title ?

Here is my models and relations:

Users
    id
    username
Item
    id
    user_id
    title_id
Item_Titles
    id
    title

User model:

  public function items()
  {
      return $this->hasMany('Item', 'user_id', 'id');
  }

Item model:

public function user(){
    return $this->belongsTo('User', 'user_id', 'id');
} 

public function title()
{
  return $this->belongsTo('ItemTitle','title_id','id');
}

ItemTitle model:

public function item()
{
  return $this->hasMany('Item', 'title_id', 'id');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire