Sobes.tech
Middle+

What is the name of the method chaining pattern in Laravel (User::where()->orderBy()->get()) and what do the methods inside it technically do to make the chain work?

sobes.tech AI

Answer from AI

This pattern is called "Method Chaining." In Laravel, for example, in Eloquent ORM, methods like where(), orderBy(), get() are implemented so that each of them returns the query object itself (usually $this), allowing the next method to be called on the same object.

Technically, each method modifies the internal state of the object (for example, adding conditions, sorting, etc.) and returns the same object. This allows accumulating query parameters sequentially, and finally, for example, get() executes the query and returns the result.

An example of a simplified implementation:

class Query {
    protected $conditions = [];
    protected $order = null;

    public function where($field, $value) {
        $this->conditions[] = [$field, $value];
        return $this; // return the current object for chaining
    }

    public function orderBy($field) {
        $this->order = $field;
        return $this;
    }

    public function get() {
        // here, SQL is formed and executed based on $conditions and $order
        return "Query result";
    }
}

$query = (new Query())->where('id', 1)->orderBy('name')->get();
What is the name of the method chaining pattern in… - sobes.tech