When you need to call this kind of shared protected methods from the same class boot method, for example to be reused in a global scope an error occurs like this :
Non-static method App\Product::withCalculatedPricingScope() should not be called statically
but you can avoid it with this useful trick
if ( ! function_exists('outer_scope')) {
class guestClass23c7d2389d6839b0dcd53a8230d04b35{};
/**
* Easily changes closure scope to an extraneous
*
* @param $closure
* @param null $thisPointer
* @param string $scope
* @return mixed
*/
function outer_scope($closure,$thisPointer=null,$scope=\guestClass23c7d2389d6839b0dcd53a8230d04b35::class){
return $closure->bindTo($thisPointer,$scope);
}
}
// Reuse as global scope
class Product {
// ....
protected static function boot()
{
parent::boot(); // TODO: Change the autogenerated stub
self::addGlobalScope(outer_scope(function($query){
Product::withCalculatedPricingScope($query);
}));
}
// ....
// Our actual scope, which will continue to work in exactly the same way as before
public scopeWithCalculatedPricing( $query, $include_tax = false ) {
$this->withCalculatedPricingScope( $query, $include_tax );
}
protected function withCalculatedPricingScope( $query, $include_tax = false ) {
$tax_multiplier = $include_tax ? 1.2 : 1;
$query->selectRaw( 'products.*, ( products.price * ' . $tax_multiplier . ' ) as total_price' )
->where( 'stock', '>', 0 );
}
}