Home > Net >  When to use ::query in Laravel model?
When to use ::query in Laravel model?

Time:06-20

I can use User::where() and User::query()->where()

With a query I get hints in IDE. But are there any other benefits or guidelines?

CodePudding user response:

there is no benefit other than the IDE recognizing the initiation of a query builder instance.

As there is no benefits in not using it, since doing User::where() will call the magic method:

// Illuminate\Database\Eloquent\Model
public static function __callStatic($method, $parameters) //$method = "where"
{
    return (new static)->$method(...$parameters);
}

Which calls the magic method

// Illuminate\Database\Eloquent\Model
public function __call($method, $parameters) //$method = "where"
{
    if (in_array($method, ['increment', 'decrement'])) {
        return $this->$method(...$parameters);
    }

    if ($resolver = (static::$relationResolvers[get_class($this)][$method] ?? null)) {
        return $resolver($this);
    }

    return $this->forwardCallTo($this->newQuery(), $method, $parameters); //<---- and will end in here
}

While User::query() is

// Illuminate\Database\Eloquent\Model
public static function query()
{
    return (new static)->newQuery();
}

So using User::query() helps the IDE and leads to less steps but basicly it's the same thing. (performance difference between both methods is negligible in our times)

  • Related