使用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'));
}
}
答案 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'));
}