How to get table prefix in Laravel 4.2 - BOOKC -->

How to get table prefix in Laravel 4.2

Wednesday, March 22, 2017


On your database configuration (app/config/database.php), you can specify a prefix for every table that you use on your database, the question is how to get this table prefix dynamically without making it hardcoded.

Lucky for us, laravel 4.2 provides a way to get this table prefix, we can use the DB class in laravel and then call the static method getTablePrefix(). But before that, let me show you how to specify the table prefix.

You can specify the table prefix on app/config/database.php, let's say you use mysql then enter the prefix you desired on the connection settings.
  'mysql' => array(

'driver' => 'mysql',

'host' => 'localhost',

'database' => 'laravel42',

'username' => 'root',

'password' => '',

'charset' => 'utf8',

'collation' => 'utf8_unicode_ci',

'prefix' => 'mx_',

),

I use prefix 'mx_' as shown above, to get the prefix in laravel you can do this:
 $prefix = DB::getTablePrefix();

The prefix is stored in variable called $prefix, you can use the prefix when you need to do raw query in laravel, here's an example:
$builder->where(function($query) use ($user)        
{
$prefix = DB::getTablePrefix();

$query->whereRaw("{$prefix}categories.merchant_id in (select m2.merchant_id from {$prefix}merchants m2

where m2.user_id=?)", array($user->user_id));

});