Sometimes, omitting a database column from a database query result is the desired result when using Laravel. This is mostly done by request of a customer or to hide certain information from a user. This can be done in Laravel in two ways, using Laravel model options and through the eloquent query builder. Eloquent ORM is an ActiveRecord implementation for working within your database. This makes it easy to use lingo close to natural language to express and query your database.

  1. Omitting the desired database column using the hidden array on a model, for example:
/**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
        'created_by'
    ];

From the code above, the ‘created_by’ column will be hidden from all queries involving the model. Yes, all the queries involving the model. So only use this when you are sure you will not require a specific database column in the eloquent model to show in your queries.

2. Using the ‘makeHidden()’ collection method on an eloquent query, for example:

$this->model->where('created_by', 1)->get()->makeHidden(['created_by']);

In the above example, the ‘created_by’ column is not hidden using the hidden array like in the first example. This means the column is present in all queries made to the model. Thus to remove it from our query result, the ‘makeHidden()’ collection method is used to hide the ‘created_by’ column from the result of the query.

Using these two methods, you are able to control what database columns are seen in API and UI. Thus making it easier to create some security measures when it comes to the information seen and interacted with by the user.

Here are some of my posts in case you want to read more. I hope this helps someone in their project. Bye ?.

Categorized in:

Programming,

Last Update: March 21, 2024