Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make a scope in laravel that calls various other scopes?

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?

like image 679
geoffs3310 Avatar asked Sep 21 '15 12:09

geoffs3310


People also ask

What is global scope in laravel?

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.

What are query scopes in laravel?

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.

What is local scope in laravel?

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).

What is scope filter in laravel?

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).


1 Answers

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);
}
like image 126
ceejayoz Avatar answered Oct 02 '22 05:10

ceejayoz