Martney Acha
Martney Acha

Reputation: 3002

How to Declare a Different Database Connection in laravel Controller

I have a Controller and I need to set the Database for my Query Builder, all is working but when I create new function I need to redeclare a connection, What I need is to declare the connection so that the whole controller will be connecting with that database.

class CompanyInformationController extends Controller
{



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function firstFunction()
    {

     $connection = DB::connection('fdis_1');

      return  $connection->getDatabaseName();

    }

    public function secondFunction()
    {
     // This is redundant
     $connection = DB::connection('fdis_1');

      return  $connection->getDatabaseName();

    }
}

Upvotes: 1

Views: 876

Answers (1)

Ravindra Bhanderi
Ravindra Bhanderi

Reputation: 2936

in a class on controller

 private $connection;

 public function __construct()
    {
        $this->connection = DB::connection('fdis_1');

    }

now use into your method like

  $this->connection->getDatabaseName();

Upvotes: 4

Related Questions