laravelenvironment-variableslaravel-8laravel-service-container

How to bind .env values in Laravel Service using Service Container and Service Provider


What I want to achieve is I have a service class name 'SmsService'

<?php
namespace App\Services;

use App\Contracts\SmsServiceContract;
use App\Models\Student;
use Twilio\Rest\Client;

    class SmsService implements SmsServiceContract{
    
            private $account_sid;
            private $account_token;
            private $account_from;
            private $reciever;
    
            public function __construct(){
                $this->account_sid = env("TWILIO_SID");
                $this->account_token = env("TWILIO_TOKEN");
                $this->account_from = env("TWILIO_FROM");
                $this->reciever = new Client($this->account_sid, $this->account_token);
            }
    
        public function sendSingleSms($phone_number, $message){
            
            $this->reciever->messages->create($phone_number,[
                'from' => $this->account_from,
                'body' => $message
            ]);
        }
    
    }

I'm binding this service in a service container like this.

$this->app->bind(SmsServiceContract::class, SmsService::class);

The issue is that I'm getting null when I'm trying to get TWILIO_SID from .env file. How could I get .env data in SmsService class?


Solution

  • You should never access env variables directly in your application, but only through config files.

    The best place to put these is in config/services.php

    Add a section for Twilio;

        'twilio' => [
            'sid' => env('TWILIO_SID'),
            'token => env('TWILIO_TOKEN'),
            'from' => env('TWILIO_FROM'),
        ] 
    

    then open tinker and run

    >>> config('services.twilio')
    

    and check that the values are all represented there as expected.

    Then in your service provider change references to env() for config and using the dot separated names. eg;

        public function __contruct(){
           $this->account_sid = config('services.twilio.sid');
           $this->account_token = config('services.twilio.token');
           $this->account_from = config('services.twilio.from);
    

    finally, make sure you bind your class into the container via the register() method of a service provider.