Get Dynamic Table Name And Pass It As Parameter In DB Query

Hell Artisan guys, in this brand new tutorial i will show you how we can fetch table name dynamically in Laravel. Look we call it statically. We we use DB query to fetch data we put table name statically. But in this example i will show you how you can fetch table name dynamically.

Look normally we fetch data using query builder which is look like this. 



But you know that we can get table name dynamically using getTable() method. 



If you visit the below path then you will get the Model.php file. Just press control f and search getTable() method. you will see the below code. 


 protected $table;

 public function setTable($table)
    $this->table = $table;

    return $this;

 public function getTable()
    return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this)));


Look what is happening? User or all models extends Model. So we can call getTable() method using the model instance. 

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Model


So now of course we can access it like below to get table name dynamically. Let's see 

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


You can also get it via container like below. 

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


If you use the above method then no need to pass table name. Just pass the model instance and call the getTable() method. Hope it can help you.


#laravel #query-builder #laravel-8x #eloquent-tips