global variable for all controller and views

后端 未结 16 2110
Happy的楠姐
Happy的楠姐 2020-11-27 15:54

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following

public function __construct() 
{
             


        
16条回答
  •  [愿得一人]
    2020-11-27 16:24

    There are two options:

    1. Create a php class file inside app/libraries/YourClassFile.php

      a. Any function you create in it would be easily accessible in all the views and controllers.

      b. If it is a static function you can easily access it by the class name.

      c. Make sure you inclued "app/libraries" in autoload classmap in composer file.

    2. In app/config/app.php create a variable and you can reference the same using

      Config::get('variable_name');

    Hope this helps.

    Edit 1:

    Example for my 1st point:

    // app/libraries/DefaultFunctions.php
    
    class DefaultFunctions{
    
        public static function getSomeValue(){
         // Fetch the Site Settings object
         $site_settings = Setting::all();
         return $site_settings; 
        }
    }
    
    //composer.json
    
    "autoload": {
            "classmap": [
    ..
    ..
    ..  
            "app/libraries" // add the libraries to access globaly.
            ]
        }
    
     //YourController.php
    
       $default_functions  = new DefaultFunctions();
        $default_functions->getSomeValue();
    

提交回复
热议问题