如何使用构造函数在Laravel中创建和传递属性


How to use a Constructor to create and pass a property in Laravel

使用Laravel:我希望在所有方法中都有特定的属性可用,而不必在每个方法中复制代码。所以…我想也许把代码放进构造函数是正确的做法。可能不是这样,因为它没有按预期工作。PHPStorm使构造函数中的$contractor变量变灰,告诉我它在任何地方都没有使用。然而,指数法中的承包商美元变量并没有变灰。尽管如此,我没有在Index()中使用$contractor变量。

我做错了什么?

这是构造函数:

class AccountController extends Controller {
    protected $contractor;
    protected $email;
    protected $id;
    public function __construct(Contractor $contractor, Auth $id)
    {
        $this->id = Auth::id();
        $user = User::find($this->id);
        $contractor = Contractor::where('email', '=', $user->email)->get();
    }
    public function index($contractor) // THIS DOES NOT WORK
    {
        return View('contractor_portal/account_show', compact('contractor'));
    }
}

这就是你的做法:

public function __construct(Contractor $contractor, Auth $id){
    $this->id = Auth::id();
    $user = User::find($this->id);
    $this->contractor = Contractor::where('email', '=', $user->email)->get();
}
public function index()
{
    $contractor = $this->contractor;
    return View('contractor_portal/account_show', compact('contractor'));
}