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

时间:2015-11-20 17:47:29

标签: php constructor laravel-5.1

使用Laravel:我希望在我的所有方法中都可以使用特定属性,而无需在每个方法中复制代码。所以..我想也许把代码放到构造函数中是正确的。它可能不是因为它没有按预期工作。 PHPStorm已经在构造函数中灰显了$ contractor变量,告诉我它在任何地方都没有使用。然而,Index方法中的$ contractor变量并不是灰色的。然而,我没有得到$ contractor变量用于Index()。

我做错了什么?

这是构造函数:

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'));
    }
}

1 个答案:

答案 0 :(得分:0)

这是你这样做的方式:

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'));
}