hretic hretic - 4 months ago 7
PHP Question

how does laravel finds the connection between models and its table in database

in my model i have

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model
{
//
}


in my controller i can say
Page:all()
and get all the rows from
pages
table
but i dont see any connection between
Page
model and
pages
table in the database

does it just guess table name based on the model name (lower case with extra s at the end ) or it's mentioned somewhere else ?

Answer

As you can see in the docs, this is the magic of Laravel :-)

https://laravel.com/docs/5.2/eloquent#defining-models (see Table Names)

If you want, you can set another name manually by user the following

protected $table = 'my_table_name';

And to go a bit further, this is how Laravel gets the table name in the base Model you can found at /vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

/**
 * Get the table associated with the model.
 *
 * @return string
 */
public function getTable()
{
    if (isset($this->table)) {
        return $this->table;
    }

    return str_replace('\\', '', Str::snake(Str::plural(class_basename($this))));
}
Comments