Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
Olof84 Avatar asked Aug 19 '16 10:08

Olof84


2 Answers

Use this in your query :

(new YourModel())->getTable()

Example :

DB:raw('SELECT * FROM '.(new User())->getTable().' WHERE id=3');
like image 69
neoteknic Avatar answered Nov 17 '22 11:11

neoteknic


If you already have a queryBuilder object you can obtain the table name like

$tableName = $query->getModel()->getTable();

like image 24
Olotin Temitope Avatar answered Nov 17 '22 11:11

Olotin Temitope