Robo Robok
Robo Robok

Reputation: 22683

How to set bindings for DB::raw?

In Laravel 5.7, I'm having an Eloquent query like this:

return User::findOrFail($userId)
    ->dogs()
    ->setBindings(['', '', '', '', $userId])
    ->get([
        'name',
        DB::raw('coalesce(birth_year, ?) <> ? as birth_year')
        DB::raw('coalesce(breed, ?) <> ? as breed')
    ]);

It's a little simplified example, but what I need in general, is passing the bindings to DB::raw().

My example works, but I don't like the fact that I need to manually overwrite $userId that is supposed to come naturally from user-dogs relation. Also, I don't like it that all bindings are together.

Is there a better way to use DB::raw like in my example? I know there is a selectRaw, but I don't want to select all the columns raw.

Upvotes: 1

Views: 1529

Answers (1)

Paras
Paras

Reputation: 9465

The selectRaw adds a raw select expression. It does not select all the columns raw. It also has a second param for bindings, so you can use this:

return User::findOrFail($userId)
    ->dogs()
    ->select('name')
    ->selectRaw('coalesce(birth_year, ?) <> ? as birth_year', ['', ''])
    ->selectRaw('coalesce(breed, ?) <> ? as breed', ['', $userId])
    ->get();

Upvotes: 1

Related Questions