Michel Gisenaël
Michel Gisenaël

Reputation: 351

Laravel eloquent make visible only given attribute in one instance of model

i have instance model from

$model = Model::find(1);

for example this instance always return these attribute (some is from $append):

-id
-name
-countRelation
-description
-created_at
-updated_at

what i want is to only retrive name and description from this instance;

makeVisible only work to show hidden attribute; i don't want use makeHidden because the result of find may change if on model i add new append attribute;

Upvotes: 0

Views: 2836

Answers (5)

Kevin Njenga
Kevin Njenga

Reputation: 61

I found makeVisible(array $column) working better for me.

$model->makeVisible(['wallet']);

Upvotes: 0

lagbox
lagbox

Reputation: 50561

Since you are appending accessors limiting the SELECT statement won't stop those from being appended to the serializied output. You can use setVisible to do this though:

$model->setVisible(['name', 'description']);

Setting what is visible this way will limit the attributes, appends and relationships that are returned in the serialized output of the Model.

Upvotes: 1

Aless55
Aless55

Reputation: 2709

You can use select() to select only certain columns in your query.

$model = Model::select('name', 'description')->find(1);

https://laravel.com/docs/8.x/queries#specifying-a-select-clause

You can also get the Model and use functions on the model. If you have a single Model you can use get().

$model = Model::find(1)->get('name', 'description');

If you have a collection you can use ->map->only(). This maps the only function as a callback for each Model in your Collection.

$models = $models->map->only(['name', 'description']);

Upvotes: 0

Kaushik Mallik
Kaushik Mallik

Reputation: 1

if you retrieve name and description only, then you may use

$model = Model::select(['name', 'description'])->find(1);

Upvotes: 0

atma
atma

Reputation: 214

You can use select to only retrieve some column in your database, it will not affect append, see the doc for more info Eloquent

$model = Model::find(1);
// to this
$model = Model::select('name', 'description')->find(1);

See Query Builder for more insight about grabbing data from database.

Upvotes: 0

Related Questions