dongzangchui2072 2017-04-04 08:09
浏览 150
已采纳

如何在Laravel中设置全局变量(不用弄乱迁移)?

I just want to Fetch Title and Tagline of the site from options table of my Database.
I tried Fetching it from AppServiceProvider.php but it shows Error that table does not Exist when I delete all the tables and run PHP artisan migrate.

I also tried Session but Finally, it takes me to the old AppServiceProvider.php method. It works fine but not when we install the Application fresh and run migration!

This is how my AppServiceProvider.php Looks like to get Idea what Exactly I want to do.

public function boot()
{
    $site_options = array();

    $site_title = Options::where('option_name','site_title')->first();
    $site_options['site_title'] = $site_title?$site_title->option_value:'Site Title';

    $site_tagline = Options::where('option_name','site_tagline')->first();
    $site_options['site_tagline'] = $site_tagline?$site_tagline->option_value:'A Simple website!';

    view()->share('site_options',$site_options);
}

I am searching for the answer on Stackoverflow and everywhere but I don't know what to do. I can also Create constructor on all the Controllers and Fetch the Data but then I have to pass the variables with every view and that makes the code look Bad!

Any Standard Solution for this?

PS: Seeding Does not work when I've this code Added into the AppServiceProvider.php nor Migration works. I have to Remove this code from AppServiceProvider.php in order to migrate and seed!

  • 写回答

1条回答 默认 最新

  • doumao1887 2017-04-04 08:13
    关注

    Can you use a try catch on it?

    try {
        $site_title = Options::where('option_name','site_title')->first();
        $site_options['site_title'] = $site_title->option_value;
    } catch (\Exception $e) {
        $site_options['site_title'] = 'Site Title';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器