我想进一步了解如何利用这个特性的强大功能,即可以将模型作为一个空对象传递,该对象已经实例化并随时可以使用。
我面临的问题是可重用性,我不想写两次这个函数。
因此,让我们以下面的函数为例:
API
Route::post('/onboarding/email-verification', 'CustomerController@verifyEmail');控制器
public function verifyEmail(Request $request, Customer $customer) {}上面的函数有一个简单的用途,它允许我使用我已经从http请求接收到的Request实例,其中我有一个实例化对象为$request,在这里我可以进一步使用。
现在,在同一个控制器中,我希望使用verifyEmail(),作为$this->verifyEmail(),但我不能使用,因为函数需要两个参数,所以我尝试重新构建这个函数,如下所示:
$this->verifyEmail(new Request(['email' => $customer->email]), new Customer()) -因为该函数需要一封电子邮件。我尝试过许多其他的迭代,但是即使它们确实工作了,它们看起来也很可怕。
所以我的问题很简单,你怎么能重复使用一个Laravel函数,它是由模型/对象构建的。
谢谢
发布于 2018-12-25 15:04:59
您可以使用第三个参数:
public function verifyEmail(Request $request, Customer $customer, ?string Email)
{
if ($email) {
// use var
} else {
// use request
}
}您只需插入请求以使用它,或使$request参数为空:
$this->verifyEmail($request, new Customer(), 'youremail@test.com')如果要保留2个参数,可以定义新的$request变量,如下所示:
$request = new \Illuminate\Http\Request();
$request->replace(['email' => 'email@totest.com']);
$this->verifyEmail($request, new Customer());https://stackoverflow.com/questions/53923398
复制相似问题