【问题标题】:Laravel 5.x override views for specific usersLaravel 5.x 覆盖特定用户的视图
【发布时间】:2019-08-03 07:29:06
【问题描述】:

我正在尝试根据登录用户 theme 覆盖视图。我们有一个themes 表,每个用户都有一个theme 的FK。

我的目录结构如下:

- resources
  - themes 
    - my_custom_theme
  - views

我已经创建了自己的ViewServiceProvider 的副本,并且正在扩展原始副本。这很好用,我正在覆盖registerViewFinder(),这也很好用。但是在应用程序周期的这个阶段,auth()->user() 没有设置,所以我无法获得他们的主题。

    /**
     * Register the view finder implementation.
     *
     * @return void
     */
    public function registerViewFinder()
    {
        $this->app->bind('view.finder', function ($app) {

            //dd($app['config']['view.paths']);

            //dd(auth()->user()->theme);

            return new FileViewFinder($app['files'], $app['config']['view.paths']);
        });
    }

我想根据登录的用户主题生成一个路径,所以它可以从这个目录加载。 resources/themes/my_custom_theme.

如果我无法访问此处的用户,那么预期的解决方法是什么?

非常感谢

【问题讨论】:

    标签: php laravel laravel-5 laravel-blade templating


    【解决方案1】:

    我能够通过使用路由中间件覆盖视图来实现这一点。在此之前的任何内容都无法访问Auth::user()

    <?php
    namespace App\Http\Middleware;
    
    use Illuminate\View\FileViewFinder;
    
    class SwitchTheme
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @param  string|null  $guard
         * @return mixed
         */
        public function handle($request, \Closure $next, $guard = null)
        {
            if (auth()->check()) {
                $paths = \Config::get('view.paths');
                $base = resource_path('themes');
                $theme = auth()->user()->theme;
    
                // add custom view path to the top of the path stack
                array_unshift($paths, "$base/$theme");
    
                // create a new instance of the Laravel FileViewFinder and set.
                $finder = new FileViewFinder(app()['files'], $paths);
                app()['view']->setFinder($finder);
            }
    
            return $next($request);
        }
    }
    

    我得到现有的视图路径数组,并从数据库中检索用户主题。取消移动新路径,在我的例子中是resource_path/theme_name

    我找不到重置路径的方法,使用$finder-&gt;addLocation 会将您的主题路径放在堆栈的底部,因此它不会被覆盖。在这种情况下,我需要创建一个新的 FileViewFinder 实例,为其提供新的路径数组,然后覆盖app()['view'] 上的现有查找器。

    简单易用,只需一个中间件。

    要加载,只需将\App\Http\Middleware\SwitchTheme::class 添加到Kernel.php 中的$middlewareGroups 数组中

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2013-07-06
      • 2015-07-04
      • 2020-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多