Josh Petitt
Josh Petitt

Reputation: 9589

How to temporarily hide model relations attributes with Laravel 5

I have read how to temporarily hide model attributes. I would like to temporarily hide a model relation attribute.

For instance

{
    "slug": "google-chrome",
    "name": "Google Chrome",
    "description": {
         "text": null,
         "created_at": "2016-12-05 12:16:38",
         "updated_at": "2016-12-05 12:16:38"
}

What is the syntax for hiding the description.created_at only in this query? In my SoftwareController I have

public function show(Request $request, $slug)
{
    $models = Software::query();

    $model =
        $models
        ->where('slug', $slug)
        ->firstOrFail()
        ->makeHidden([
            'description.created_at',
        ]);

    return $model;
}

This syntax does not seem to work? Is it possible?

Upvotes: 0

Views: 1644

Answers (1)

Elias Soares
Elias Soares

Reputation: 10264

makeHidden() doesn't support dot notation.

You should call makeHidden on your related model:

$model = $models
        ->where('slug', $slug)
        ->firstOrFail();

$model->description->makeHidden('created_at');

Note that this will only work when you have a single result. If you want to do this on a Collection, you must iterate on the itens and run makeHidden for each item you have.

Upvotes: 4

Related Questions