R
R
runprogr2020-08-09 16:28:07
Laravel
runprogr, 2020-08-09 16:28:07

How does magic work in Laravel?

Laravel has Model::find() , Model::where() methods that work just like $model->find(), $model->where() .

If you go to the Eloquent source and search for find() - https://github.com/illuminate/database/search?q=fi... , you can see that such a method exists in the Query/Builder and Eloquent/Collection classes . There are no such methods in the model class https://github.com/illuminate/database/blob/2edbe3... , as well as in all the traits that are included in it.

And if there are no methods, then the method works

public static function __callStatic($method, $parameters)
{
        return (new static)->$method(...$parameters);
}

Behind him works
public function __call($method, $parameters)
    {
        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 then, apparently, somehow an instance of Query / Builder is created and methods are already called in it? Where in the code does this happen?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2020-08-09
@runprogr

return $this->forwardCallTo($this->newQuery(), $method, $parameters);

A
Alexey Ukolov, 2020-08-09
@alexey-m-ukolov

how is an instance of Query/Builder created and methods already called in it? Where in the code does this happen?
(new static)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question