【发布时间】:2019-02-25 19:53:12
【问题描述】:
我有两个控制器。学生控制器和教师控制器。我有一个变量$chat,我想将它传递给StudentController 和TeacherController 的所有视图。 $chat 将包含这两个控制器的不同数据。
我搜索并找到了方法,但我得到的是空数据。我就是这样做的。
<?php
namespace App\Http\Controllers;
use View;
class StudentController extends Controller {
public function __construct()
{
$this->middleware('auth')->except(['home']);
$this->middleware('access')->except(['home']);
$chats = studentChat();
View::share('chats', $chats);
}
所以,我在这里打印,它返回一个空数组,但是当我在函数中使用它时,数组包含数据。这里有什么问题?有人可以帮忙吗?
我尝试了什么:
public function boot()
{
View::composer('*', function ($view) {
$chats = Cache::remember('chats', 60, function () {
if(Auth::user()->user_type() == config('constant.student'))
{
return studentChat();
}
else
{
return teacherChat();
}
});
$view->with('chats', $chats);
});
}
【问题讨论】:
-
我相信 View::share 只有在服务提供商中使用时才有效。我只需在构造函数中使用您的数据设置 $this->chats 的属性,然后使用 with() 手动将其传递给控制器内的所有视图
-
嗯,我知道那种方法,但想知道更简单的方法。
-
@Rob 将
studentChat()代码置于问题中 -
@J.Doe 现已添加。
-
@Rob 我认为你的查询返回 null,试试
DB::enableQueryLog(); studentChat(); dd(DB::getQueryLog());- 这是你的原始 sql 查询,分析一下
标签: laravel