Framework: Macro on \Illuminate\Database\Query\Builder always returns $this

Created on 4 Nov 2017  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.19
  • PHP Version: 7.1

Description:

macro on Builder

\Illuminate\Database\Query\Builder::macro("toSqlWithBindings", function(){
            $sql = $this->toSql();
            foreach($this->getBindings() as $binding)
            {
                $value = is_numeric($binding) ? $binding : "'$binding'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }
            return $sql;
        });

usage:

        dd(User::select('*')->toSqlWithBindings());

returns instance of Builder instead of sql string as expected.
is it intentional or am I making something wrong?

Most helpful comment

For others having this problem like me:
What themsaid is saying is that you need to do \Illuminate\Database\Eloquent\Builder::macro() instead of \Illuminate\Database\Query\Builder::macro(), or possibly both.

All 3 comments

You need to register the macro on the Eloquent service provider if you want to use it like this, so yeas you might end up having two versions of the same macro one for the Query builder and another for the Eloquent builder. This is by design.

@themsaid I made it work fine like this - please check it out. I think it's worth including in the core. What do you think? It works similar to dump() and dd() on Collection chain.
I can make a PR if it's worth it.

For others having this problem like me:
What themsaid is saying is that you need to do \Illuminate\Database\Eloquent\Builder::macro() instead of \Illuminate\Database\Query\Builder::macro(), or possibly both.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghost picture ghost  路  3Comments

progmars picture progmars  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

gabriellimo picture gabriellimo  路  3Comments