Sling Academy
Home/PHP/Eloquent: 5 Ways to Exclude Specific Columns from Query Result

Eloquent: 5 Ways to Exclude Specific Columns from Query Result

Last updated: January 17, 2024

Introduction

Laravel’s Eloquent ORM is a powerful and elegant way to interact with your database. Often times, you may need to exclude specific columns from your query results for optimization, security, or data transformation purposes. This article will explore several methods to achieve this in Laravel.

Use ‘select’ with Specific Columns

Specify the columns you want instead of the ones you wish to exclude.

  1. Begin your query using the ‘select’ method.
  2. List the columns you want to include in your results.
  3. Execute the query as usual to get results with only the specified columns.

Example:

// only select 2 columns 'name' and 'email'
User::select('name', 'email')->get();

Notes: Efficient and straightforward; however, you must know which columns you need in advance.

Use ‘hidden’ Property on the Model

Define attributes that should be hidden across all queries for a given model.

  1. In the Eloquent model, specify a hidden property as an array.
  2. Add the names of the columns you wish to exclude to this array.
  3. Retrieve your data as usual; the specified columns will be excluded automatically.

Example:


// Example in User model
protected $hidden = ['password'];

// Query
User::all();

Notes: Great for columns that should always be hidden, such as passwords, but not flexible for one-off queries.

Use ‘makeHidden’ on Collection Results

Dynamically hide attributes from JSON output on a per-query basis.

  1. After obtaining a collection from the query, chain the makeHidden() method.
  2. Provide an array of the column names you wish to exclude.
  3. Return or use the modified collection as needed.

Example:


// makeHidden 'password'
User::all()->makeHidden(['password']);

Notes:This method is superb for ad-hoc queries; however, the columns are only hidden in the JSON representation.

Raw Query with Excluded Columns

Directly write a raw SQL query specifying the columns you wish to include:

  1. Write your query using the DB::select method and exclude certain columns.
  2. Be wary of security implications such as SQL injection.
  3. Execute the raw SQL to the database.

Example:

// columns 'name' and 'email'
$results = DB::select(DB::raw('SELECT name, email FROM users'));

Use Query Scopes for Reusability

Define query scopes on your models to encapsulate query logic:

  1. Add a function in your Eloquent model that returns a modified query.
  2. Use the select method to specify the columns to include.
  3. Apply the scope whenever you want to exclude certain columns.

Example:


// In User model
public function scopeWithoutPassword($query)
{
    return $query->select('name', 'email');
}

// Usage
User::withoutPassword()->get();


Conclusion

In summary, Laravel provides various ways to exclude columns from Eloquent queries, each with its own use-cases and trade-offs. Whether you’re using ‘select’ and ‘hidden’ features, leveraging collection methods like ‘makeHidden’, or writing custom queries and scopes, Laravel offers the flexibility and power to optimize the data your application retrieves and processes. Carefully consider which method is most appropriate for your specific situation for the best balance between functionality, performance, and security.

Next Article: Working with one-to-many relationships in Eloquent (with examples)

Previous Article: Laravel Eloquent: 3 Ways to Check if a Record Exists

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array