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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。