Maxcot Maxcot - 2 months ago 6x
PHP Question

How does tinker work in laravel with regard to database and models.?

php artisan tinker

If I type in
$owner = new carfreak\Models\CarTitle();
tinker is instantiating my laravel model, right?

But if I type in
$vehicle = carfreak\Models\Car::first();
then tinker tells me that
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'carfreak.Cars' doesn't exist (SQL: select * from 'Cars' limit 1)
.... as if it's talking direct to the database - no model involved. ?!?!?!?

(I don't have a Car or Cars model at this point, by the way)

What am I missing?


For both your questions it is not just a tinker thing but will behave the same inside a route or controller, so it is more Laravel behaviour than tinker specific.

For your first question, yes, thinker will just instantiate your model class and return it.

Then, calling Model::method and if the method does not exist on the model itself, ie. like first laravel will create an instance of Illuminate\Database\Eloquent\Builder and call the method on that query builder object.

So it becomes Illuminate\Database\Eloquent\Builder->first() which returns $this->take(1)->get($columns)->first();. That is a normal select query for the columns which then hydrates a model and returns it.

So in the background a select query first takes place, before a model is returned so your table would need to exist.