CarlosCarucce CarlosCarucce - 3 months ago 13
PHP Question

Hide children field when serializing toArray [Laravel 5.3]

I've read here (Section: Temporarily Modifying Attribute Visibility) that we can hide object properties temporarily.

Is it possible to also hide children attributes?

For example:

//User model
class User extends \App\AppModel
{
public function articles()
{
return $this->hasMany(Article::class);
}
}


Exclude from array here:

$user = User::find($id);

$userData = $user->makeHidden(['last_name', 'articles.*.user_id'])->toArray();
dd($userData); //user_id still present in articles :(

Answer
$userData = User::with('articles')->where('id', $id)->get()->each(function($user){
    $user->articles->makeHidden(['user_id']);
})->makeHidden(['last_name'])->toArray();

dd($userData);