Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent the first where clause

Tags:

php

laravel

I am wondering how Laravel implement eloquent syntax so that the first where clause can be called statically with User::where()

User::where('id', 23)->where('email', $email)->first();

Do they have a public static function where() and a public function where()

like image 520
Yada Avatar asked Oct 19 '15 10:10

Yada


2 Answers

Calling where on an Eloquent model does involve a little bit of magic that occurs behind the scenes. Firstly, take the example of:

User::where(’name’, ‘Joe’)->first;

There’s no static where method that exists on the Model class that the User class extends.

What happens, is that the PHP magic method __callStatic is called which attempts to then call the where method.

public static function __callStatic($method, $parameters)
{
    $instance = new static;

    return call_user_func_array([$instance, $method], $parameters);
}

As there’s no explicitly defined user function called where, the next magic PHP method __call which is defined in Model is executed.

public function __call($method, $parameters)
{
    if (in_array($method, ['increment', 'decrement'])) {
        return call_user_func_array([$this, $method], $parameters);
    }

    $query = $this->newQuery();

    return call_user_func_array([$query, $method], $parameters);
}

The common database related methods become accessible via:

$query = $this->newQuery();

This instantiates a new Eloquent query builder object, and it’s on this object that the where method runs.

So, when you use ```User::where()`` you’re actually using:

Illuminate\Database\Eloquent\Builder::where()

Take a look at the Builder class to see all of the common Eloquent methods you’re used to using, like where(), get(), first(), update(), etc.

Laracasts has a great in-depth (paid) video on how Eloquent works behind the scenes, which I recommend.

like image 168
Amo Avatar answered Sep 24 '22 06:09

Amo


Well let's find out.

When we open a model it extends Model so let's open that class. In the class Model we find 2 "magic" methods called __call() and __callStatic()

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

We also see in class Model it makes use of the class use Illuminate\Database\Query\Builder as QueryBuilder;

If we open the Builder class we find a method called public function where()

So if you call User::where it calls __callStatic('where', $parameters) from the Model class.

I hope this makes sense.

like image 44
Daan Avatar answered Sep 25 '22 06:09

Daan