Snippets - Laravel

Exclude columns from Query Result - Laravel

|
Anuz Pandey

What are Traits?

Traits can be seen as classes that contain frequently used functions or attributes. They serve as a solution to avoid multiple inheritance or implementing the same code through interfaces.

What are Scopes?

Scopes allow constraints to be applied to queries. There are two types of scopes: global and local. For a more comprehensive understanding, it is recommended to refer to Laravel's documentation by Taylor Otwell, as it provides the best explanation.

Implementation

To begin, we create a trait that encapsulates the logic for excluding specific columns. There is no specific location to place this file, but a common practice is to create a folder names "Traits" within the "App" directory.

Our trait consists of two methods. The first method returns an array of columns existing in the corresponding table of the model.

The second method utilizes a helper method to obtain the array of columns and then selects the difference between that array and the columns to be excluded.

Assuming you have familiarized yourself with the documentation and understand the syntax and parameters of the method, the next step is to use the trait in the desired Models when performing a select operation where column exclusion is required.

Here is an example of how to use the trait:

By incorporating this trait into your Models and specifying the columns to be excluded, you can easily control which columns are omitted when performing a select operation.

Thank you.

Keep coding, keep exploring, and keep inspiring. 🐼


  • Tags:
  • eloquent
  • laravel
  • exclude-columns