Use Laravel query builder without hard-coding the table names

Image for post
Image for post

Problem:

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

Solution:

$users = \DB::table((new \App\Models\User)->getTable())->get();
$users = \DB::table(app()->make(\App\Models\User::class)->getTable())->get();
// in the app/models/User.php fileprotected $table = 'members';

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