
Global scope in Laravel with example
Here we have some global scope examples in Laravel. Global scopes provide a convenient, easy way to make sure every query for a given model receives certain constraints. In a simple way, we can say that we can add some filter to every query for a specific model.
Answers 1
-
Use of global scope in Laravel
//app\Scopes\ActiveScope.php <?php namespace App\Scopes; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Scope; class ActiveScope implements Scope { /** * Apply the scope to a given Eloquent query builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return void */ public function apply(Builder $builder, Model $model) { $builder->where('is_active', 1); } } //app\Models\User.php <?php namespace App; use App\Scopes\ActiveScope; use Illuminate\Database\Eloquent\Model; class User extends Model { protected static function booted() { static::addGlobalScope(new ActiveScope); } } //routes\web.php Route::get('/get-active-users-using-global-scope', function(){ DB::enableQueryLog(); $users = App\Models\User::all(); dd(DB::getQueryLog()); });
0Output:
^ array:1 [▼
0 => array:3 [▼
"query" => "select * from `users` where `is_active` = ?"
"bindings" => array:1 [▶]
"time" => 4.57
]
]
Random Code Snippet Queries: Laravel
- Retrieve count of nested relationship data in Laravel
- How to fill a column automatically while creating records in Laravel
- Check if Relationship Method Exists in Laravel
- Get 30 days older records from table in laravel
- Display success message in laravel
- How to fetch single row data from database in laravel
- Get the post details if it has at least one comment in comments table
- How to get count of all records created at yesterday
- Remove public from url in laravel project
- The openssl extension is required for SSL/TLS protection but is not available
- How to check records exist in loaded relationship in Laravel blade view
- Pass value from controller to model in laravel
- Extra Filter Query on Relationships in Laravel
- Conditional where clause in Laravel
- Calculate age from date of birth in Laravel
- Print query in laravel
- How to validate website url in laravel using validaiton
- Class 'Facade\Ignition\IgnitionServiceProvider' not found
- Laravel save object to database
- How to delete record in Laravel with ajax
- How to disable timestamps in laravel
- Get previous date data in laravel
- Create model with migration and seeder
- Remove array keys and values if it does not exist in other array in Laravel
- Laravel get count with where condition