How to exclude certains columns while using Eloquent?
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Introduction
When developing applications using Laravel, you often want to retrieve data from your database efficiently by selecting only specific columns and ignoring the rest. In this article, we will provide a detailed guide on excluding certain columns when working with Eloquent models in Laravel. We'll discuss both common methods and best practices for efficient data retrieval.Excluding Columns Using Where Clauses
Laravel's Eloquent provides you with a powerful set of query builder methods that allow you to customize your database queries based on specific conditions. One method for excluding columns is by using the 'whereNotIn' and 'whereNull' methods. Here are some examples: 1. Excluding columns in a single relationship:php
$users = User::where('gender', 'M')->where('is_active', 1)->whereHas('posts', function ($query) {
$query->where('title', 'not', 'How to use Eloquent');
})->get(['pseudo', 'email', 'age', 'created_at'])->toArray();php
$users = User::where('gender', 'M')->where('is_active', 1)->has('posts.comments')->whereDoesntHave('posts.comments', function ($query) {
$query->whereHas('commenter.status', function ($query) {
$query->whereIn('status', ['verified', 'approved']);
});
})->get(['pseudo', 'email', 'age', 'created_at'])->toArray();Excluding Columns Using the get() Method
Another approach to exclude columns is by manipulating the result set after retrieving it from the database. You can achieve this by overriding the 'get' method and excluding unwanted columns in your data: 1. Exclude specific columns using array indexes:php
$users = User::where('gender', 'M')->where('is_active', 1)->get(['pseudo', 'email', 'age', 'created_at'])->toArray();php
$users = User::where('gender', 'M')->where('is_active', 1)->get()->map(function ($user) {
$selectedColumns = ['pseudo', 'email', 'age', 'created_at'];
return collect($user)->only($selectedColumns)->toArray();
})->toArray();