Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

LARAVEL: How the Models Know which Database to Access?

I was watching the http://teamtreehouse.com/library/laravel-basics/laravel-and-databases/eloquent-orm video and became to have doubts about how is set the link between models and databases? I Undertand that when you use the same name for Controllers and Models, the framework understands that both have a correlation. But how the framework knows which database that correlates to these two, if database names are different?

1 Answer

In app > config > database.php, you have something like this:

<?php

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'forge',
            'username'  => 'forge',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

?>

The application uses one database, with multiple tables. The database connection is made in this file for the live application. When you're working locally, you might have a local folder setup in app > config > local > database.php where you will find your local database connection information for working locally.

Inside a model file ( app > models > any-model-file.php), you can select a specific table like so:

<?php
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'todo_lists';
?>

If you haven't explicitly given a table name inside your model file, here's what laravel will do for you:

"The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table."

Read more

Thanks! It answered my question.