nowox
nowox

Reputation: 29178

Hide foreign id column in an Eloquent relationship

Let's consider the Einstein's Puzzle and these two models:

class Pet extends Eloquent
{
    public function pet()
    {
        return hasOne(Man::class)
    }
}

class Man extends Eloquent
{
    public function pet()
    {
        return belongsTo(Pet::class)
    }
}

If I want to get all the Pets:

Pet::all()->toArray();

I'll get for instance:

{
    id: 2,
    man: {
        nationality: "German",
        pet_id: 2
    }
    name: "Fish"
}

Having the pet_id column is irrelevant in that case and I would like to hide it. How?

Upvotes: 1

Views: 843

Answers (2)

piyush
piyush

Reputation: 85

class Pet extends Eloquent
{
    public function pet()
    {
        return hasOne(Man::class)->select('nationality');
    }
}

Upvotes: 1

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28583

Use Eloquent API Resources to get an array version of your Models. This is more flexible in the long run than relying on the toArray method of the model which will not be configurable.

If you still want to use toArray, you can simply add the attributes that should not be included to a protected member variable called $hidden in each corresponding model (See documentation about serialization of Eloquent models).

Upvotes: 1

Related Questions