2

How do I Transform specific fields in Laravel?

For example:

$user = \Auth::User();
return [
    'user_id'  => $user->id,
    'articles' => $user->articles,
    'pages'    => $user->pages,
];

$user->articles will show the entries the articles table and $user->pages from the pages table.

In the User model, it would be defined something like that:

public function articles()
{
    return $this->hasMany(Article::class);
}

I do not want to return all the fields from $user->articles, just id, name, and description. What is good way to transform this collection?

I would like to do something like:

'articles' => transformArticle($user->articles),
I'll-Be-Back
  • 10,530
  • 37
  • 110
  • 213

2 Answers2

1

In the relationship:

 return $this->hasMany('Article::class')->select(array('id', 'name','description'));  

Or whenever you need it:

User::with(array('articles'=>function($query){
        $query->select('id','name','description');
    }))->get();
Sanzeeb Aryal
  • 4,358
  • 3
  • 20
  • 43
0

Transformers

maybe you need this.

LaravelFly
  • 53
  • 7