0
0
Laravelframework~10 mins

Query scopes in Laravel - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a local query scope named active in a Laravel model.

Laravel
public function scopeActive($query) {
    return $query->where('[1]', 1);
}
Drag options to blanks, or click blank then click option'
Aactive
Bstatus
Cenabled
Dis_active
Attempts:
3 left
💡 Hint
Common Mistakes
Using the scope name 'active' as the column name instead of the actual column.
Using a column name that does not exist in the database.
2fill in blank
medium

Complete the code to apply the active scope to a query in a Laravel controller.

Laravel
$users = User::[1]()->get();
Drag options to blanks, or click blank then click option'
Aactive
BwhereActive
CscopeActive
DfilterActive
Attempts:
3 left
💡 Hint
Common Mistakes
Calling the scope method with the 'scope' prefix like scopeActive().
Using a non-existent method like whereActive().
3fill in blank
hard

Fix the error in the scope definition by completing the missing part to allow chaining.

Laravel
public function scopePopular($query) {
    return $query->[1]('votes', '>', 100);
}
Drag options to blanks, or click blank then click option'
Aselect
Bfilter
Cwhere
DorderBy
Attempts:
3 left
💡 Hint
Common Mistakes
Using filter which is not a query builder method.
Using select which changes selected columns instead of filtering.
4fill in blank
hard

Fill both blanks to create a global scope class that orders users by creation date descending.

Laravel
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');
    }
}
Drag options to blanks, or click blank then click option'
AorderBy
Bwhere
Ccreated_at
Dupdated_at
Attempts:
3 left
💡 Hint
Common Mistakes
Using where instead of orderBy for sorting.
Using updated_at instead of created_at.
5fill in blank
hard

Fill all three blanks to define and use a local scope recent that filters users created within the last 7 days.

Laravel
public function scopeRecent($query) {
    return $query->where('[1]', '>=', now()->[2]([3]));
}

// Usage:
$recentUsers = User::recent()->get();
Drag options to blanks, or click blank then click option'
Acreated_at
BsubDays
C7
Dupdated_at
Attempts:
3 left
💡 Hint
Common Mistakes
Using updated_at instead of created_at.
Using addDays instead of subDays.
Passing a string '7' instead of a number 7.