我在Laravel中使用Model Factories嘲笑一些数据。我需要在Eloquent each
方法中使用外部变量,但是当我运行代码时,我在该行上得到Undefined variable
异常。
这是我的代码:
$myVar = 45;
$collection = factory(MyClass::class, 5)->create()->each(function ($item) {
// I need to use $myVar in here ...
});
有什么想法吗?
答案 0 :(得分:2)
试试这个
$myVar = 45;
$collection = Factory(MyClass::class, 5)->create()->each(function ($item) use ($myVar){
// Use it however you want
});
答案 1 :(得分:0)
$1