Selecting and Aliasing Columns in Laravel

When you want to select specific columns using Eloquent or Query Builder in Laravel, no one would blame you for reaching for sleect() or selectRaw(). But, did you know that you can specify column to select in the all(), get(), and first() methods as well? What’s more, aliasing columns, no matter how they are selected, works exactly as you’d expect. Here’s a “cheat sheet” for all the ways you can select (and alias!) columns:

Be careful to pass your bindings to the second parameter of selectRaw(). From the docs:

$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();

Leave a Comment

Your email address will not be published. Required fields are marked *