视图作曲家不在laravel 5.6中工作

时间:2018-04-18 05:25:22

标签: laravel

我正在为所有视图创建一个通用的作曲家,但它无法正常工作。

App/Http/ViewComposers

中为作曲家创建目录

MovieComposer.php内创建ViewComposers

namespace App\Http\ViewComposers;

use Illuminate\View\View;

class MovieComposer
{
    public $movieList = [];

    public function __construct()
    {
        $this->movieList = [
        'Movie One',
        'Movie Two',
        'Movie Three',
        'Movie Four',
        'Movie Five'
        ];
    }

    public function compose(View $view)
    {
        $view->with('latestMovie', 'Hello');
    }
}

为作曲家创建服务提供者

php artisan make:provider ComposerServiceProvider

在提供程序中的config / app.php中注册ComposerServiceProvider

App\Providers\ComposerServiceProvider::class,

ComposerServiceProvider.php

内的代码
namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // View::share('latestMovie', 'Hello world');

        View::composer('app', 'App\Http\ViewComposers\MovieComposer@compose');

        // view()->composer('app', function($view){
        //     $view->with('latestMovie', 'Hello world');
        // });

        // view()->composer(
        //   'app',
        //   'App\Http\ViewComposers\MovieComposer'
        // );
    }

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

在此代码中 latestMovie 变量是全局变量,在所有视图中使用,但它无法正常工作。

错误。

  

ErrorException(E_ERROR)   未定义变量:latestMovie(查看:/home/rupendrakumardhiman/Projs/badass/resources/views/layouts/app.blade.php)(查看:/home/rupendrakumardhiman/Projs/badass/resources/views/layouts/app.blade。 PHP)

2 个答案:

答案 0 :(得分:0)

尝试将视图编辑器附加视图更改为select t1.key, t1.key2, t1.name, t2.name, t3.name from table1 t1 left join table2 t2 on t1.key = t2.key left join table3 t3 on t1.key = t3.key where t1.key = '123' group by t1.key

layouts.app

或通配符视图

View::composer('layouts.app', 'App\Http\ViewComposers\MovieComposer@compose');

答案 1 :(得分:0)

View::composer('app', 'App\Http\ViewComposers\MovieComposer@compose');

您不应使用最终的@compose。如果问题仍然存在,请确保在“资源/视图”目录中有一个名为“ app”的视图(视图文件的名称)。