I have a model in Laravel that has various scopes defined. I want to use all of them in a lot of places so rather than chaining them together I'd rather just be able to call one scope that calls all of the other scopes like so:
function scopeValid($query, $user_id) {
$query = $this->scopeDateValid($query);
$query = $this->scopeMaxUsesValid($query);
$query = $this->scopeCustomerMaxUsesValid($query, $user_id);
return $query;
}
This doesn't seem to work though, is there a way to achieve this?
Global Scope is a very important concept of laravel 6. using Global Scope you can reuse same eloquent condition in laravel application. i also written tutorial of how to create local scope in laravel 6. Local scope it only for single model. But you define global scope then you can use with all model.
The scope is just a method that you can use in your model to encapsulate the syntax used to execute a query such as above. Scopes are defined by prefixing the name of a method with scope, as below.
Scopes allow you to define prebuilt scopes (filters) that you can use either every time your query a model with a specific method chain (Local Scope).
Laravel Scope methods provide us to wrap some code of functionality inside model function. So that we can re-use that again and again where we want (only for models).
As shown in the docs, you'll want to do your scoping against $query
, not $this
, and use the scope's magic function rather than calling the internal implementation:
public function scopeTesting($query) {
return $query->testingTwo();
}
public function scopeTestingTwo($query) {
return $query->where('testing', true);
}
As a demonstration, you can see here calling the testing()
scope applies the logic in the testingTwo()
scope:
>>> App\User::testing()->toSql();
=> "select * from "users" where "testing" = ?"
>>>
So, for your code, this should do the trick:
function scopeValid($query, $user_id) {
$query = $query->dateValid();
$query = $query->maxUsesValid();
$query = $query->customerMaxUsesValid($user_id);
return $query;
// or just return $query->dateValid()
// ->maxUsesValid()
// ->customerMaxUsesValid($user_id);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With