Home
NexoPOS

Scope Class

While building CRUD components, you might have classes that are based on the same table. Therefore, you want to apply a custom scope to each component to filter how entries are retrieved.

A good example is a blog with PostCrud and MyPostCrud. Both classes use the same table, but MyPostCrud should display the posts created by the logged user. That's where Scope Classes come in.

Declaring Scope

In your module, the scope must be stored in the "Scopes" directory. While this is not a requirement, we highly encourage this approach. The definition of a scope follows the same structure as a regular Laravel scope. Here is an example of how scopes are declared:


<?php
namespace Modules\MyModule\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Database\Query\Builder;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class MyPost implements Scope
{
    public function apply( Builder | QueryBuilder $builder, Model $model )
    {
        $builder->where( 'author', Auth::id() );
    }
}

Using Scopes On Classes

Now that we've defined our scope, we can use it on any CRUD class we would like to apply it. Here is how to proceed:


<?php
namespace Modules\MyModule\Crud;

use App\Services\CrudService;
use App\Classes\CrudScope;
use Modules\MyModules\Scopes\MyPost;

#[ CrudScope( MyPost ) ]
class MyPostCrud extends CrudService
{
    // internal class definition
}