How to use more than one query scope in Laravel

Created at 10-Jan-2022 , By samar

How to use more than one query scope in Laravel

In this article, we will see how to solve "How to use more than one query scope in Laravel".

You can use (call) more than one query scope in Laravel after defining the query scopes in the model. You can call the multiple query scopes using the chaining method.
  • Chaining query scopes in Laravel

    --PATH app\Models\User.php
    <?php
    
    namespace App\Models;
    
    use Illuminate\Contracts\Auth\MustVerifyEmail;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Support\Facades\Event;
    
    class User extends Authenticatable
    {
    
        public function scopeActive($query) {
            return $query->where('active', 1);
        }
        
        public function scopeRegisteredWithinDays($query, $days) {
            return $query->where('created_at', '>=', now()->subDays($days));
        }
    
    }
    
    //Calling query scopes method
    $users = App\Models\User::registeredWithinDays(30)->active()->get();
    

    Chaining query scopes will help you to use the multiple scopes while querying the model. You can get the user records from the users table which are created within 30 days and are active (active column has value 1).

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.