Use Laravel query builder without hard-coding the table names

Arman Ahmadi
2 min readFeb 15, 2021

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.

$users = \DB::table('users')->get();

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 :

$users = \DB::table('members')->get();

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:

$users = \DB::table((new \App\Models\User)->getTable())->get();

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

$users = \DB::table(app()->make(\App\Models\User::class)->getTable())->get();

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:

// in the app/models/User.php fileprotected $table = 'members';

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 :)

--

--