Home » Php » php – Laravel – how do you access App object in a custom class?

php – Laravel – how do you access App object in a custom class?

Posted by: admin July 12, 2020 Leave a comment


I have a custom class in app/libraries/data/Data.php where i want to return a connection to a database.

The problem is i need to dynamically load a database that doesn’t(and can’t) exist in the config file.

I found a nice solution, and to be honest it was exactly what i was hoping for, but it seems i cant access the App object from there.

namespace libraries\data;
use DB;

class Data 

    public function db($name, $firma = false)

        if ($name == 'firma') {

            $config = App::make('config');
            $connections = $config->get('database.connections');

            $newConnection = $connections[$config->get('database.firma_%s')];

            $name = sprintf('firma_%s', $firma);
            $newConnection['database'] = $name;

            App::make('config')->set('database.connections.'.$name, $newConnection);

        return DB::connection($name);

Update: of course i tried “use App;” (d`oh) and of course it didn’t work. And of course it works now.

How to&Answers:

You could also use the app() helper function which returns the application instance. And $config = app('config'); to get the config object.


Your are in the namespace libraries\data. Either you add use App; or you call the App methods with \App::.


Since you define a custom namespace libraries\data , the application will try to find the App class in the libraries\data namespace.

If you want to use the laravel App class you need to write this:

 $config = \App::make('config');

Or add use App; at the top of your file like you did with the DB class.