Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

laravel

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.

<?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 "use App;" (d`oh) and of course it didn't work. And of course it works now.

like image 1000
razvansg Avatar asked Jan 08 '15 15:01

razvansg


1 Answers

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

like image 107
Robert Bakker Avatar answered Sep 29 '22 15:09

Robert Bakker