如何在 eloquent each 方法中使用外部变量?
How do I use an external variable inside an eloquent each method?
我正在使用 Laravel 中的模型工厂模拟一些数据。我需要在 Eloquent each
方法中使用外部变量,但是当我 运行 代码时,我在该行得到了 Undefined variable
异常。
这是我的代码:
$myVar = 45;
$collection = factory(MyClass::class, 5)->create()->each(function ($item) {
// I need to use $myVar in here ...
});
有什么想法吗?
试试这个
$myVar = 45;
$collection = Factory(MyClass::class, 5)->create()->each(function ($item) use ($myVar){
// Use it however you want
});
我正在使用 Laravel 中的模型工厂模拟一些数据。我需要在 Eloquent each
方法中使用外部变量,但是当我 运行 代码时,我在该行得到了 Undefined variable
异常。
这是我的代码:
$myVar = 45;
$collection = factory(MyClass::class, 5)->create()->each(function ($item) {
// I need to use $myVar in here ...
});
有什么想法吗?
试试这个
$myVar = 45;
$collection = Factory(MyClass::class, 5)->create()->each(function ($item) use ($myVar){
// Use it however you want
});