【问题标题】:How to access a field data from users table from a controller in Laravel?如何从 Laravel 中的控制器访问用户表中的字段数据?
【发布时间】: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!它解决了我的问题。非常感谢。
  • 这能回答你的问题吗? PHP parse/syntax errors; and how to solve them
  • 一个小建议,永远不要在控制器中使用$this->middleware();,因为这是route 的职责(允许访问或运行任何中间件),而不是控制器......如果你能访问那个控制器,那么就意味着路由层允许你,你看到我的逻辑了吗?

标签: php laravel


【解决方案1】:

最后,我不得不按照@John 的建议将代码行auth()->user()->site 移动到构造函数旁边的index() 函数。还从控制器中删除了middleware 并添加到web.php

public function __construct(){
    $this->today = date("Y-m-d");        
}

public function index(){
    $this->sites = Helper::getSites(auth()->user()->site);
    return view('division.dashboard.index')->with($data);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多