Use Laravel query builder without hard-coding the table names

Problem:

There might be sometimes that you want to use Laravel query builder instead of the Eloquent either because of performance issues or the complexity of the query. The first problem you might have seen using the query builder could be hard coding the table names everywhere you want to use the query.

The above code will work perfectly until you have used this code snippet in many places, and now you want to change the name of your tables. In this case, for example, we might want to change our table name from users to members , so you have to find all the queries and change all of their table names to members :

Solution:

The solution is really simple and straightforward. Laravel provides a public method called getTablefor all models that are extending the Illuminate\Database\Eloquent\Model class.

First of all, you need to create an instance of the model manually:

Alternatively, Laravel’s service container can do it for you:

Now if you want to change the name of the User Model’s table you can easily use the protected property in the model called table:

Note: It’s recommended to use the models' name + ‘s’ for the table names, but this article is provided to prevent you from hard-coding the table names in the business logic of your application.

Thanks for reading this article! I hope you enjoyed it :)

Backend developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store