Even though table names don't change often, if you need to reference them in your Laravel application, it makes sense to fetch them from the model directly. Then, when they do change, there's less to go wrong.
Let's look at the quick solution, then create a trait to make this easier to use elsewhere.
Here's the one-off way to grab a table name from a model.
(new Post())->getTable(); // returns 'posts'
And if you already have the model instance, it works in the same way.
$post = Post::find(1);
$post->getTable(); // returns 'posts'
Unfortunately, the getTable
method can't be called statically, so if you want to access the table name without instantiating first, we'll need a helper.
To make things easier, you could add a method to access a Laravel model's table name statically directly on the model.
Add a helper method to your model like this:
class Post extends Model
{
//...
public static function getTableName()
{
return with(new static)->getTable();
}
}
Notice we're using a slightly different method name, since getTable
already exists in the base Model
class.
Now, you're able to access the table name of your model statically!
Post::getTableName(); // returns 'posts'
Chances are you'll want this functionality added for every model. Instead of littering each model with a method and repeating ourselves, let's create a trait, so we can apply it where we need it.
trait StaticTableName
{
public static function getTableName()
{
return with(new static)->getTable();
}
}
Next, apply this to your model. Nothing needs to change about the implementation, since it just uses new static
and the underlying getTable
method.
class Post extends Model
{
use StaticTableName;
}
Our functionality still works in the same way, but now we can quickly apply this trait to any model.
Post::getTableName(); // returns 'posts'
And we're done! This is an easy, neat way to access the table name of our models in Laravel, with a few different methods.