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

LukeHsu's avatar

DB:raw,selectraw Are they the same?

HI there , I just learn Laravel for 3 months and confuse the "DB:raw" and "selectraw", what is the different between them? when I wrote the query below $users = bicmappingdata::selectraw('sum(qty) as qty,salename,cusname')->where('SaleType', '=','A2')->GroupBy('salename','cusname')->get();

the result would be the same like below

$users = bicmappingdata::select(DB::raw('sum(qty) as qty'),'salename','cusname')->where('SaleType', '=','A2')->GroupBy('salename','cusname')->get();

What is the different between "DB:raw" and "selectraw" and which one is better to use?

0 likes
3 replies
gregrobson's avatar

They are almost the same. selectRaw allows bindings... looking at the source code:

    // Line 232, /Illuminate/Database/Query/Builder.php
    public function selectRaw($expression, array $bindings = [])
    {
        $this->addSelect(new Expression($expression));
        if ($bindings) {
            $this->addBinding($bindings, 'select');
        }
        return $this;
    }

    // Line 835 /Illuminate/Database/Connection.php
    public function raw($value)
    {
        return new Expression($value);
    }

Based on the method signatures

// You can do bindings with selectRaw()
->selectRaw('complex_thing(column_name, ?)', [123]);

// but there's not a way to do bindings with DB::raw()
->select(DB::raw('no_bindings_allowed('fixed', 'values', 42)');

You could manually insert a value into the DB::raw() string above, but you need to validate to make sure that code injection is not possible.

1 like

Please or to participate in this conversation.