Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Get DB Prefix

In Laravel 4 I could do this to get the table prefix:

$prefix = DB::getTablePrefix();

What's the equivalent in L5?

like image 823
sterfry68 Avatar asked Apr 08 '15 02:04

sterfry68


1 Answers

As discussed in the comments, the issue was not that the method was not accessible from the facade, but rather the facade was not being called correctly in the base namespace.

Using \DB::getTablePrefix() or placing use \DB as DB at the top of the document solves the problem.

As requested, I will describe the steps I took to ensure the method was still accessible through the facade:

  1. Check the facade is still there. The facades are registered in the config/app.php file and refer to a PSR-4 namespace of the class behind the facade

  2. Check what class the facade points at. This is a little more tricky and requires a little bit of intelligent guesswork. First, I accessed the facade definition using the PSR-4 class name from step 1. That points to this file in the Laravel source. This simply sets the facade to point to an object in the "Service Container" named "db"

    In order to find what registers this service, I had to guess the service provider which is registered in the config/app.php file. There's a service called Illuminate\Database\DatabaseServiceProvider which is the only thing I saw related to database, so I guessed that. This is also a PSR-4 class name so you can find the file pretty easily in the Laravel source here

    I can see in this service provider that "db" is registered as a DatabaseManager.

  3. Investigate the service that the facade is fronting. DatabaseManager is not specifically namespaced in the service provider and therefore must exist in the same namespace, which means it'll be in the same folder in the source. I opened up the DatabaseManager and looked for the method getTablePrefix. I didn't find it, but I did find a __call magic method that will proxy to another object accessed with $this->connection().

    Looking at the connection method, I can see from the PHPdoc block on this method that it returns a \Illuminate\Database\Connection which is a PSR-4 class name (again). It's also in the same namespace as the DatabaseManager I'm looking at. I opened this file and found the method you're looking for.

It might seem like a bit of effort to find if the facade still provides access to a method, but using a good IDE (PHPStorm in my case) and knowing the basics about it (which I hopefully described here) means you can look these things up in less than a minute.

One of the major advantages of Laravel 5 (and PSR-4) is that all the class names and namespaces should resemble the file system so everything should be pretty intuitive.

like image 82
Scopey Avatar answered Oct 22 '22 02:10

Scopey