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.

Answers 1
  • 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();
    
    0

    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