Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating clean formatted json with Laravel pivot tables

So I'm running tables with localization but I keep the strings in a separate "master" table.

Say I have a table for each entity:

Products
  id
  price
  ...

a translation table

Translations
  id
  name
  description
  ...

a relationship table

product_translation
  product_id
  translation_id
  lang --enum('en', 'es', 'fr',...)

Problem: the not so pretty json that comes with this

So I've created a BaseModel which uses a many to many relationship:

public function translations()
{
  return $this
  ->belongsToMany('Translation')
  ->where('lang', '=' App::getLocale());
}

So with that I can do Product::with('translations')->get() for my json. However...

What I wanted

{
    "name": "Foo",
    "description": "Bar",
    "price": "1000",
    "stock": "10",
}

What I got

{
  "id": "1",
  "price": "1000",
  "stock": "10",
  "translations": [
    {
      "id": "1",
      "name": "Foo",
      "description": "Bar",
      "pivot": {
        "product_id": "1",
        "translation_id": "1"
      }
    }
  ]
}

As you can see there's just too much baggage with the output. How do I restrict which fields I want to produce my desired json output?

EDIT: Discovered https://github.com/laravel/framework/issues/745

So using $hidden I am able to hide specific fields. Neat.

EDIT: Using $appends with a getNameAttribute() accessor method I'm able to create a new property to my json. Problem solved!

like image 537
tiffanyhwang Avatar asked Feb 08 '14 11:02

tiffanyhwang


1 Answers

That is the code that should be added to the class Product (As answered in the question itself):

class Product {

    protected $hidden = ['id', 'translations'];

    protected $appends = ['name', 'description'];

    public function getNameAttribute()
    {
        return $this->translations->name;
    }

    public function getDescriptionAttribute()
    {
        return $this->translations->description;
    }

}
like image 61
Alaeddin AL Zeybek Avatar answered Sep 27 '22 16:09

Alaeddin AL Zeybek