global variable for all controller and views

后端 未结 16 2145
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:13

    You can also use Laravel helper which I'm using. Just create Helpers folder under App folder then add the following code:

    namespace App\Helpers;
    Use SettingModel;
    class SiteHelper
    {
        public static function settings()
        {
            if(null !== session('settings')){
              $settings = session('settings');
            }else{
              $settings = SettingModel::all();
              session(['settings' => $settings]);
            }
            return $settings;
        }
    }
    

    then add it on you config > app.php under alliases

    'aliases' => [
    ....
    'Site' => App\Helpers\SiteHelper::class,
    ]
    

    1. To Use in Controller

    use Site;
    class SettingsController extends Controller
    {
        public function index()
        {
            $settings = Site::settings();
            return $settings;
        }
    }
    

    2. To Use in View:

    Site::settings()
    

提交回复
热议问题