simmbiote's avatar

Using table prefixes in Laravel?

Does Laravel support the use of table prefixes? I.e. if I set a prefix in the .env, the migrations will prepend the prefix to the table? So if my prefix was abc_ and I referred to a table as products in the code (eg. Schema::create('products', function (Blueprint $table) {...) it would actually refer to abc_products?

0 likes
11 replies
moharrum's avatar

You can setup table prefix in config/database.php,

    'prefix' => '',

And yes it will prepend the prefix to the table, if you want to set prefix in your .env file you can:

.env

...
DB_TABLE_PREFIX=abc
...

and in config/database.php

    'prefix' => env('DB_TABLE_PREFIX', 'abc')
4 likes
simmbiote's avatar

Thanks for the info. It would be useful if config/database.php was already set to 'prefix' => env('DB_TABLE_PREFIX') so that one need only change the .env file on first installation

jekinney's avatar

@simmbiote why? That's another call to the env file that probably less then one percent do. Plus that probably should be hard coded in.

1 like
michaeldyrynda's avatar

I'd suggest that your prefix won't (shouldn't) change between environments. Set a string value in config/database.php and be done with it.

2 likes
simmbiote's avatar

@deringer what's the reason for that? Is it a good idea or not in general to use prefixes with laravel? @jekinney is it slower to refer to the env file?

jekinney's avatar

Not nesesary but as your file gets larger yes.

Any case to ensure every deploy or use of your apps code something like table prefix should be hard coded. What if you swap servers and forget. As the env is not in source control, be easy to forget. It's not a security issue as like db login info that's different per server anyways.

Prefix is a constant, never changing once set.

1 like
michaeldyrynda's avatar

You can make the prefix whatever you want it to be, but it's shouldn't change between instances of your application. Ideally, your application's tables belong in a single database. If you're mixing multiple applications into a single database, I'd advise against that.

nomadme's avatar

How do you prefix in the migration, so your tables gets prefixed accordingly during migration run?

pmall's avatar

@nomadme do not use dynamic prefix, it is useless. Hardcode them.

3 likes
davestead's avatar

@PMALL - That's not helpful; we need a dynamic schema name prefix or some other solution for our database, based on client site.

You don't state why prefix is useless.

We're using Laravel 5.7 and I'm new to Laravel.

Please or to participate in this conversation.