Skip to content

Dynamically set a Laravel model's table name

Posted on:03/12/2022

If you wish to set a model’s table name dynamically you can override the \Illuminate\Database\Eloquent\Model::getTable method.

If you’re developing a package it’s typical to use your package’s configuration file to define model table names. This config. file can then be published and customised by the user.

// config/foo.php
return [
    'table_name' => 'bar',
];
// app/Models/Foo.php
public function getTable(): string
{
    return config('foo.table_name', parent::getTable());
}

Don’t forget to update the \::up and \::down methods in your database migrations.

use Illuminate\Support\Facades\Schema;

Schema::create(config('foo.table_name')...
Schema::dropIfExists(config('foo.table_name'));

You can see an example of this usage in Spatie’s renowned Laravel Permissions package here: #1, #2.