Laravel 5.6在一组路由中通过Service Provider注入变量

时间:2018-07-06 09:38:35

标签: php laravel laravel-blade

我有一部分网站以特定的前缀/manage开头。 我能以某种方式像AppServiceProvider一样,在所有使用该前缀的路由中注入一个变量吗?

我试图通过将这个变量传递给所有路由的布局来做到这一点。但是后来我遇到了一个问题。我在特定页面的刀片视图中使用了此变量,它返回了variable not defined。 然后,我检查了laravel调试器,并看到了刀片文件的加载顺序。那是: 1. Current page view 2. Layout view 3. Sidebars and other stuff 因此,当前页面在布局之前加载的事实会导致undefined variable的错误。

那么,我该如何解决呢?谢谢。

我的服务提供商提供的代码:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\CT;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(['website.implicare.ct.show', 'website.implicare.ct.petition.index', 'layouts.ct'], function($view) {
            $ct = request()->ct;

            $permissions = [];
            foreach($ct->userPermissions(auth()->id()) as $userPermission) {
                if($userPermission->pivot->ct_id == $ct->id) {
                    array_push($permissions, $userPermission->name);
                }   
            }

            $view->with('permissions', $permissions);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

1 个答案:

答案 0 :(得分:0)

创建ComposerServiceProvider

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public $theme = 'mytheme';

    public function boot()
    {

        view()->composer($this->theme.'.includes.navbar', 'App\Http\ViewComposers\MenuComposer');
       view()->composer($this->theme.'.includes.header', 'App\Http\ViewComposers\MenuComposer');

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}