How to use more than one query scope in Laravel
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).
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: Laravel
- How to add foreign key in laravel using migration
- How to get only time from created_at in laravel
- Generate unique username in Laravel
- How to remove P tag from CkEditor in Laravel?
- How to get id of next record in laravel
- Call to a member function pluck() on array
- Call to undefined method App\Models\User::follow()
- Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
- Laravel create multiple records in Pivot table
- How to get data from two tables in laravel
- How to insert multiple rows in mysql using loop in laravel?
- How to display a specific word from a string in laravel
- How to create static page in Laravel
- Call to a member function pluck() on null
- Print query in laravel
- How to check column value of a record is null or not in laravel
- How to get route method name in Laravel
- How to add dynamic page title in Laravel view
- How to use or operator in laravel
- Class 'App\Providers\Auth' not found
- How to add active class to menu item in laravel
- How to check relationship is loaded or not in Laravel
- Redirect to another view from controller in laravel
- Non-static method App\Http\Helper::myFunction() should not be called statically
- Best Practices for Error Handling in Production Server Code (example code)