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. 

DB::table('users')->get()

 

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

get-table-name-dynamically-in-laravel

 

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. 

vendor\larave\framework\src\illuminate\database\eloquent\Model.php

  
 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.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.