Laravel is owned by ToMany to return only certain columns

Thus, I have many relationships between users and photos through a pivot table user_photo. I use belongsToMany('Photo')in my user model. However, the problem is that I have a dozen columns in my photo table that I no longer need (especially during the json response). An example would be:

//Grab user #987 photos:
User::with('photos')->find(987);
//json output:
{
  id: 987,
  name: "John Appleseed",
  photos: {
    id: 5435433,
    date: ...,
    name: 'feelsgoodman.jpg',
    ....// other columns that I don't need
  }
}

Is it possible to change this method so that the model Photosreturns only accepted columns (for example, given by an array ['name', 'date'])?

User.php

public function photos()
{
  return $this->belongsToMany('Photo');
}

Note. I want to select only certain columns only with User->belongsToMany->Photo. When you do something like Photo::all(), yes, I would like all the columns to be normal.

EDIT: , "()" Laravel Eloquent, . https://github.com/laravel/laravel/issues/2306

+4
3

, Photos, , , - . , , JSON, .

1: / toArray() Eloquent ( toJson()) . , , , select() .

2. JSON toJson(). /, .

3. API ajax , , , League/Fractal, . ( API, .)

+1

, user_id. :

public function photos()
{
    return $this->belongsToMany('Photo')->select(['id', 'user_id', 'date', 'name']);
}

, .

0

attribToMany select laravel.

public function photos()
{
  return $this->belongsToMany('Photo')->select(array('name', 'date'));
}
0

Source: https://habr.com/ru/post/1525931/


All Articles