Laravel - how do you access an App object in a custom class?

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

The problem is that I need to dynamically load a database that does not exist (and cannot) in the configuration file.

I found a good solution, and frankly, that is what I was hoping for, but it seems I can’t access the App object from there.

<?php
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 using the application; (d`oh), and of course it didn't work. And of course it works now.

+4
source share
3 answers

libraries\data. use App;, \App::.

+4

app(), . $config = app('config');, .

+3

Because you define your own \ data name libraries, the application will try to find the App class in the \ data library namespace.

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

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

Or add use App;to the beginning of the file, as was the case with the DB class.

+1
source

Source: https://habr.com/ru/post/1570473/


All Articles