Harry Su
Harry Su

Reputation: 169

Laravel difference between Model, Builder and Collection

I came across this code snippet on Laravel doc

// Retrieve a model by its primary key...
$flight = App\Flight::find(1);

// Retrieve the first model matching the query constraints...
$flight = App\Flight::where('active', 1)->first();

where and find are builder functions, why App\Flight as a Model can call these function. And what are the differences between Model, Builder and Collection in Laravel?

Upvotes: 2

Views: 3770

Answers (1)

fubar
fubar

Reputation: 17388

You're able to call Builder functions on an Eloquent model, because the Model class uses the magic __call method.

As you can see in the method definition below, if the method doesn't exist on the class, or it's not increment or decrement, a new Builder query is created, on which the method is called.

public function __call($method, $parameters)
{
    if (in_array($method, ['increment', 'decrement'])) {
        return $this->$method(...$parameters);
    }
    try {
        return $this->newQuery()->$method(...$parameters);
    } catch (BadMethodCallException $e) {
        throw new BadMethodCallException(
            sprintf('Call to undefined method %s::%s()', get_class($this), $method)
        );
    }
}

https://github.com/illuminate/database/blob/master/Eloquent/Model.php#L1439

As for the difference between a Model, Builder and Collection:

Model: This follows the pattern where a model is essentially an instance of a database row, allowing you to create, update and delete a single row.

Builder: This is a layer of abstraction between your application and the database. Typically it's used to provide a common API for you to build platform agnostic database queries. E.g. they'll work on MySQL, Postgres, SQL Server, etc.

Collection: This is basically an array on steroids. It provides a chainable API for standard array_* type PHP functions, together with other useful functions for manipulating a collection of data.

Upvotes: 5

Related Questions