Lifetime access is $100 off. Ends this week.Join here →

How to get the table name from a model in Laravel

April 18th, 2024

Table names don't change often, but it's still nice to reference table names directly from your Eloquent models, so you don't end up with a bunch of hardcoded table names.

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 access a Laravel model's table name statically, 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'

Instead of littering each model with a method, 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! — a super easy and neat way to access the table name of our models in Laravel, with a few different methods.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.