Laravel-mongodb: remove _id field from result

Created on 25 Mar 2014  路  7Comments  路  Source: jenssegers/laravel-mongodb

How can I remove ( unselect ) _id field from result.
basicly db.users.find({},{"_id" : 0});

Thanks

Most helpful comment

@prashant-pokhriyal you could do something like this
protected $hidden = ['_id'];

All 7 comments

Probably through a raw operation or mark it as hidden in your model, check out https://github.com/jenssegers/Laravel-MongoDB#raw-expressions

@jenssegers did you add any functionality for this specific issue or still we have to do this by raw way

@prashant-pokhriyal you could do something like this
protected $hidden = ['_id'];

@ssatz thank you for your response but it's not always that I don't want it in the result.

I've been tinkering with this.. Anyone has a sample of a raw query with the _id field being hidden? I've tried a bunch of different ways and haven't been able to hide it with a raw query.

The only way I managed to get it to work is with a query scope.. IE:
public function scopeHideid($query){ $query->getQuery()->projections = [ '_id'=>0, ]; return $query; }

@ssatz thank you for your response but it's not always that I don't want it in the result.

You have 3 choices
1.- Raw query
2.- Duplicate Model with hidden in one of them for the specific cases
3.- You could remove _id after query

$models = MyModel::get(['field1']);
        foreach ($models as $model) {
            unset($model->_id);
        }

We have a number of methods that set or change the $hidden and $visible attributes on a model. You could add something like this to your base Model class:

/**
 * Make the given, typically visible, attributes hidden.
 *
 * @param  array|string  $attributes
 * @return $this
 */
public function makeHidden($attributes)
{
    $attributes = (array) $attributes;
    $this->visible = array_diff($this->visible, $attributes);
    $this->hidden = array_unique(array_merge($this->hidden, $attributes));

    return $this;
}

and then call it via something like:

$models = MyModel::query()->get();
$models->each->makeHidden(['id']);
Was this page helpful?
0 / 5 - 0 ratings