When you want to select specific columns using Eloquent or Query Builder in Laravel, no one would blame you for reaching for select()
or selectRaw()
. But, did you know that you can specify the column(s) 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