Search code examples
laraveldatabase-tablelaravel-query-builder

Laravel Query builder and table names


I noticed that I write the database table names quite a lot, and in different files, when I use the Query Builder. If I were to change the database table names, I would have to search and change quite many rows in my project. Is this an issue your Laravel guys noticed and come up with an solution to?

I like the Eloquent approach which uses class models, instead of database names; but for some queries I think the Query Builder is a better solution (though I am no expert in this matter).


Solution

  • How about using OOP concept. Laravel is a framework, so no one stops you from using basic PHP OOP concept. This is what I do:

    Consider my query is like :

    $result=DB::table('myTable')->select()->get();
    

    What I do is make a class that holds all the tablenames :

    class TableName
    {
        private $tableName= "myTable";
        public function getTableName()
        {
            return $this->tableName;
        }
    
        public function setTableName($table_name)
        {
            $this->tableName = $table_name;
        }
    }
    

    Now all i have to do is call a method using an object in the file I want to use the table like :

    $name = new TableName() ;
    $result=DB::table($name->getTableName())->select()->get();
    

    Use wherever you want. I don't think its the best solution however it works for me. Hope it helps