Complete the code to define a local query scope named active in a Laravel model.
public function scopeActive($query) {
return $query->where('[1]', 1);
}The local scope active filters records where the status column equals 1, indicating active items.
Complete the code to apply the active scope to a query in a Laravel controller.
$users = User::[1]()->get();scopeActive().whereActive().To use a local query scope, call the scope name as a method on the model query builder, here active().
Fix the error in the scope definition by completing the missing part to allow chaining.
public function scopePopular($query) {
return $query->[1]('votes', '>', 100);
}filter which is not a query builder method.select which changes selected columns instead of filtering.The where method filters records where the votes column is greater than 100, enabling chaining.
Fill both blanks to create a global scope class that orders users by creation date descending.
use Illuminate\Database\Eloquent\Scope; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class OrderByCreatedAtScope implements Scope { public function apply(Builder $builder, Model $model) { $builder->[1]('[2]', 'desc'); } }
where instead of orderBy for sorting.updated_at instead of created_at.The global scope applies an orderBy on the created_at column descending to sort results by newest first.
Fill all three blanks to define and use a local scope recent that filters users created within the last 7 days.
public function scopeRecent($query) {
return $query->where('[1]', '>=', now()->[2]([3]));
}
// Usage:
$recentUsers = User::recent()->get();updated_at instead of created_at.addDays instead of subDays.The scope filters users where created_at is within the last 7 days using now()->subDays(7).