Define variable and use in Laravel controller method

Updated at 03-Aug-2022, By samar

Define variable and use in Laravel controller method

Hello everyone, in this post we will examine how to solve the "Define variable and use in Laravel controller method" programming puzzle.

How can i define a variable in my laravel controller and use in controller's method. In my case i have a api key in my env file and i want to get this api key value in controller method.
  • Define variable and use in controller's method

    Create a private variable and get the value of api key from .env file using $_ENV['APP_API_KEY'] and pass the value to variable.

    app\Http\Controllers<SomeController>.php

    class SomeController extends Controller{
        private $apiKey;
        public function __construct()
        {
            $this->apiKey = $_ENV['APP_API_KEY'];
        }
    
        public function index()
        {
            $apikeyval = $this->apiKey;
        }
    
    

    .env

    APP_API_KEY = "5d1c88f1-bd63-428c-acce-eae8d1713445"
    

Back to code snippet queries related laravel