Overriding a Laravel model's default table name

  • August 24, 2015

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

I generally try to adhere to a frameworks conventions; they are after all in place to give you the opportunity to spend more time thinking about implementing cool application features instead of making mundane decisions about matters such as table names. However, you'll occasionally need to override certain conventions, such as I recently had to do in order to use a model in conjunction with a non-standard database table name. Read on to learn how this is accomplished.

Suppose your model is named Costcenter but you would like it to talk to a database table named centers. For various reasons you're unable to alter the table name and so must inform Laravel of this departure from convention. Fortunately, doing so is easy; just override the $table property in the Costcenter model like so:

class Costcenter extends Model
{

    protected $table = 'centers';

}

Incidentally, if you can in fact alter the table name without incurring any side effects, I suggest doing so. You can change a table name by creating a migration and executing the following command:

Schema::rename('centers', 'costcenters');