frankfurt-laravel
frankfurt-laravel

Reputation: 4131

How to remove fields from Laravel JSON Api response

I have an API returning an object with one-to-one relation to another object. As the models behind the objects, do have timestamps, these are also delivered when asking API.

// Get all transactions
Route::get('transaction', function() {
return Transaction::with('Personone','Persontwo')->get();
});

How do I prevent Laravel from returning the timestamps of the objects in the API?

I googled, but only found some hints to middleware or response macros but found no example pointing me into the right direction. Maybe you can help me.

Upvotes: 2

Views: 4310

Answers (2)

xReprisal
xReprisal

Reputation: 820

You can make attributes "hidden" so that they do not show up in json. docs

class Transaction extends Model
{
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = ['timestamp'];
}

Upvotes: 2

AH.Pooladvand
AH.Pooladvand

Reputation: 2059

I'm not sure if I get the question correctly but if you want to select from eager loads there are two ways

first one is inline selecting

Route::get('transaction', function () {
    return Transaction::with('Personone:id,foo,bar', 'Persontwo:id,foo,bar,foobar')->get();
});

second one is to pass a closure

Route::get('transaction', function () {
    return Transaction::with([
        'Personone' => function ($query) {
            $query->select('id', 'foo', 'bar');
        },
        'Persontwo' => function ($query) {
            $query->select('id', 'foo', 'bar', 'foobar');
        }])->get();
});

Eager Loading Specific Columns You may not always need every column from the relationships you are retrieving. For this reason, Eloquent allows you to specify which columns of the relationship you would like to retrieve:

$users = App\Book::with('author:id,name')->get();


Constraining Eager Loads Sometimes you may wish to eager load a relationship, but also specify additional query constraints for the eager loading query. Here's an example:

$users = App\User::with(['posts' => function ($query) { $query->where('title', 'like', '%first%'); }])->get(); In this example, Eloquent will only eager load posts where the post's title column contains the word first. Of course, you may call other query builder methods to further customize the eager loading operation:

$users = App\User::with(['posts' => function ($query) { $query->orderBy('created_at', 'desc'); }])->get();

Upvotes: 1

Related Questions