【发布时间】:2021-07-25 01:29:51
【问题描述】:
我有DashboardController,我需要根据登录用户的users 表中的字段site 获取仪表板数据。
这是我的控制器:
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class DashboardContoller extends Controller {
protected $today;
protected $site;
public function __construct() {
$this->middleware('auth');
$this->today = date("Y-m-d");
$this->site = auth()->user()->site; // this line is showing error
}
// Rest of my code goes here
}
当我尝试访问字段 site 时,出现“尝试获取非对象的属性‘站点’”错误。我做错了什么?
【问题讨论】:
-
Suberb,@JohnLobo!它解决了我的问题。非常感谢。
-
一个小建议,永远不要在控制器中使用
$this->middleware();,因为这是route的职责(允许访问或运行任何中间件),而不是控制器......如果你能访问那个控制器,那么就意味着路由层允许你,你看到我的逻辑了吗?