I'm running the following code in Laravel to load various relationships on my Product model:
$product->load([
'skus' => function($query){
$query->select($this->skuFields)->with([
'uniqueItem' => function($query){
// <----------reuse the code below--------->
$query->with([
'fulfillmentCenterUniqueItems',
'products' => function($query){
$query->select($this->productFields)->with([
'skus' => function($query){
$query->select($this->skuFields);
}
]);
},
'skus' => function($query){
$query->select($this->skuFields);
}
]);
// <----------reuse the code above--------->
}
]);
},
'uniqueItem' => function($query) {
//need to reuse code here
},
]);
As you can see from my note in the code, there is a place where I would like to reuse some code, so I was hoping to place it in a function, and reuse it.
Therefore, I did the following:
$uniqueItemLoadFunction = function($query)
{
$query->with([
'fulfillmentCenterUniqueItems',
'products' => function($query){
$query->select($this->productFields)->with([
'skus' => function($query){
$query->select($this->skuFields);
}
]);
},
'skus' => function($query){
$query->select($this->skuFields);
}
]);
};
$product->load([
'skus' => function($query) use ($uniqueItemLoadFunction){
$query->select($this->skuFields)->with([
'uniqueItem' => $uniqueItemLoadFunction($query)
]);
},
'uniqueItem' => function($query) {
//need to reuse code here
},
]);
However, I now receive a BadMethodCallException:
Call to undefined method Illuminate\\Database\\Query\\Builder::fulfillmentCenterUniqueItems()
This error was not occurring when the code was run the original way. This makes me think I am not using an anonymous function correctly. How can I make this work?
'fulfillmentCenterUniqueItems'function