return view($viewVariable) 来自 laravel 8 中的特征

return view($viewVariable) from a trait in laravel 8

我有一个特性被 laravel 8 中的多个控制器调用。 每个控制器都给出 return 视图的名称以及特性的功能。 如果我在特征中执行 dd($viewVariable); ,那么我会看到对视图的正确引用。但是特征拒绝 return 视图。它只是给我一个空白屏幕。一开始我以为是“无引号”、“单引号”或双引号”的问题,但我尝试了所有变体,但都没有成功。

我试过以正常方式设置视图,但它甚至拒绝渲染。我已经用 dd($var); 检查了其他函数和变量,一切正常,直到 return 视图。

ChartTrait.php

public function setViewOptionsForChartGeneration($viewVariable)
    {

        // Check which role the user has in the application
        if (Auth::user()->hasRole('admin')) {
            $recorderCollection = $this->getRecorderCollectionWhenAdmin();
            return view($viewVariable)->withRecorderCollection($recorderCollection);
        } elseif (Auth::user()->hasRole('employee|user')) {
            // Get all the valid timeslots that belongs to the authenticated user
            $userTimeslotCollection = $this->getUserTimeslot();
            // Get all the corresponding recorders from the valid timeslots that belongs to the authenticated user
            $recorderCollection = $this->onlyCollectRecordersBasedOnValidTimeslot($userTimeslotCollection);
            // return the view with all the possibility's the authenticated user has.
            return view($viewVariable)
                ->withRecorderCollection($recorderCollection->flatten())
                ->withUserTimeslotCollection($userTimeslotCollection);
        }
    }

ChartTrait.php中的函数没有问题。问题出在控制器上。您需要 return 您调用的函数来呈现视图。

trait 的正确调用方式

    public function index()
    {
        $view = "".'content.export.export'."";
        return $this->setViewOptionsForChartGeneration($view);
    }

调用特征的方式错误

    public function index()
    {
        $view = "".'content.export.export'."";
        $this->setViewOptionsForChartGeneration($view);
    }