I am setting up a payment method for a website, and I want to pass a default Braintree gateway through my entire Laravel 5 app. I have the following in my AppServiceProvider.php
, but not sure if thats where it should go or not.
public function boot() {
Schema::defaultStringLength(191);
$gateway = new Braintree_Gateway([
'environment' => env('BRAINTREE_ENVIRONMENT'),
'merchantId' => env('BRAINTREE_MERCHANT_ID'),
'publicKey' => env('BRAINTREE_PUBLIC_KEY'),
'privateKey' => env('BRAINTREE_PRIVATE_KEY')
]);
}
Should it go in that file? Or should I just set that in the BaseViewController?
This is the perfect use case for the Laravel service container.
In a service provider (you can make a new one or use the default AppServiceProvider
), you would bind a generic PaymentGateway to a specific instance of your Braintree payment gateway :
$this->app->bind('PaymentGateway', function ($app) {
return new Braintree_Gateway([...]);
});
Then, anywhere in your app where you need to use that gateway (for example, in the store() method of one of your controllers), you could do this :
public function store(PaymentGateway $gateway)
{
// Do whatever you need with the gateway
$gateway->doSomething();
}
This is a great approach because you don't need to create a new instance everytime and manually add the credentials. You can just typehint it wherever you need it and Laravel will automatically resolve it for you.