Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Crazylife's avatar

How to exclude a specific column from query when using query builder?

I am using query builder to get my data from database.

$result = DB::table('test')->..........

Instead of explicitly select all the column, is there a better way to select every column except for certain column?

0 likes
3 replies
Snapey's avatar

don't think so ? Does it really save that much? Is it a blob?

xmarks's avatar

From checking out This Answer it is not possible. However, a work-around is explained there that you might want to check out.

Otherwise, you can only specifically select the columns you want:

$result = DB::table('test')->select('id, first_name, last_name, email')->...
Sairahcaz's avatar

I wrapped a slitly changed approach from here up in a small package, cause I needed it in multiple projects:

https://github.com/laracraft-tech/laravel-useful-additions/#selectallbut

Install via composer:

composer require laracraft-tech/laravel-useful-additions

This is how it is working:

use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes;

$class = new class extends Model
{
    use UsefulScopes;

    protected $timestamps = false;
    protected $table = 'scope_tests';
};

$class->create([
    'foo' => 'foo',
    'bar' => 'bar',
    'quz' => 'quz',
]);

$class::query()->selectAllBut(['foo'])->first()->toArray();
// return ['bar' => 'bar', 'quz' => 'quz']

Note: Since you can't do a native "select all but x,y,z" in mysql, we need to query (and cache) the existing columns of the table, and then exclude the given columns which should be ignored (not selected) from the existing columns.

Cache: Column names of each table will be cached until contents of migrations directory is added or deleted. Modifying the contents of files inside the migrations directory will not re-cache the columns. Consider to clear the cache whenever you make a new deployment/migration!

Please or to participate in this conversation.