PHP code example of sajadsdi / laravel-repository

1. Go to this page and download the library: Download sajadsdi/laravel-repository library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sajadsdi / laravel-repository example snippets


use Sajadsdi\LaravelRepository\Repository;

class UserRepository extends Repository implements UserRepositoryInterface
{
    // Implement abstract methods
}

public function getModelName(): string;
public function getSearchable(): array;
public function getFilterable(): array;
public function getSortable(): array;

class UserRepository extends Repository implements UserRepositoryInterface
{
    public function getModelName(): string 
    {
        return User::class;
    }

    public function getSearchable(): array 
    {
        return ['name', 'email'];
    }
    
    public function getFilterable(): array 
    {
        return ['name', 'email', 'created_at'];
    }
    
    public function getSortable(): array 
    {
        return ['name', 'email', 'created_at'];
    }

    // other methods...
}

class UserRepository extends Repository implements UserRepositoryInterface
{
    // abstract methods...
    
    public function getVerified()
    {
        return $this->whereNotNull('verified_at');
    }
    
    public function getByName(string $name)
    {
        return $this->where('name','LIKE' , '%'.$name.'%');
    }
    
    public function getVerifiedUsersByName(string $name)
    {
        return $this->getVerified()->getByName($name);
    }
    
    // other methods...
}


//That's right, you need to inject your repository with the
//interface in the controller or each class you need.

//In this example, we create an instance of the repository
//to convey the concept.
//But it is not the right thing for real projects!
$userRepo = new UserRepository();

// Search by name or email
$users = $userRepo->search('John')->get();

// Sort by name in descending order
$users = $userRepo->sort('name:desc')->get();

// Filter between IDs
$users = $userRepo->filter('id:between_1,10')->get();

// multiple sort 
$users = $userRepo->sort('name:desc@id:asc')->get();

// multiple filter
$users = $userRepo->filter('id:in_1,10@status:is_null')->get();

$users = $userRepo->search('John')->filter('status:is_null')->sort('id:desc')->paginate(10);

protected $joinable = [
    'relationName' => [
        'rel' => [
            'table1.field1' => 'table2.field2',
            'table2.field3' => 'table3.field4',
        ],
        'join_type' => 'inner',
        'select'     => ['table2.field_x as x', 'table3.field_y as y'],
        'filterable' => ['x', 'y', 'field_z'],
        'sortable'   => ['x', 'y', 'field_z'],
        'soft_delete'=> ['table2', 'table3']
    ],
];

'rel' => [
    'table1.field1' => 'table2.field2',
],

'rel' => [
    'table1.field1' => 'table2.field2',
    'table2.field3' => 'table3.field4',
    // Extend the chain with additional table joins as necessary
],

'select' => [
    // All visible fields from the main table are automatically selected.
    
    'table2.field_x as x',  // Specific field with a clear alias
    'table3.field_y as y',  // Another field with its own alias
    // Add more fields and aliases accordingly
],

'filterable' => [
    'x',        // Alias defined in `select`
    'y',        // Another alias defined in `select`
    'field_z',  // Field from the final table in the join chain
    // Add more filterable fields as needed
],
'sortable' => [
    'x',        // Alias that's sortable
    'y',        // Another sortable alias
    'field_z',  // Field from the final table (`table3`) that's sortable
    // Add more sortable fields as 

'softDeletes' => [
    'table2',  // Related table with soft-delete enabled
    'table3',  // Another related table with soft-delete
    // List additional related tables with soft-delete enabled as necessary
],


// Apply filters and sorting on the related models
$users = $userRepo->filter('relationName.x:[email protected]:lower_100')
                   ->sort('relationName.field_z:desc')
                   ->paginate(10);

// This will fetch users with the following conditions applied:
// - For the related model under 'relationName':
//   - Field 'x' should be `null` (is_null condition).
//   - Field 'y' should be less than or equal to 100 (lower_100 condition).
// - The resulting users will then be sorted in descending order
//   based on field 'field_z' from the related model.
// - The results will be paginated, returning 10 users per page.

class UserRepository extends Repository implements CrudRepositoryInterface,UserRepositoryInterface
{
    use Crud;
    
    // other methods...
}

interface UserRepositoryInterface extends CrudRepositoryInterface
{
    //you methods...
}


class UserRepository extends Repository implements UserRepositoryInterface
{
    use Crud;
    
    // other methods...
}

interface UserReadRepositoryInterface extends ReadCrudRepositoryInterface
{
    //you methods...
}


class UserReadRepository extends Repository implements UserReadRepositoryInterface
{
    use ReadCrud;
    
    // other methods...
}

//OR

interface UserWriteRepositoryInterface extends WriteCrudRepositoryInterface
{
    //you methods...
}


class UserWriteRepository extends Repository implements UserWriteRepositoryInterface
{
    use WriteCrud;
    
    // other methods...
}

public function create(array $data)
{
    // Call the `create` method on the query builder provided by `$this->query()`
    return $this->query()->create($data);
}

interface UserRepositoryInterface
{
    public function getAll(string $search = null, string $filter = null, string $sort = null, int $perPage = 15);
    
    public function getProfilePic(int $userId);
    
    public function getUserWithAllRelations(int $userId);
}



class UserRepository extends Repository implements UserRepositoryInterface
{

    protected $joinable = [
        'activities' => [
            'rel' => [
                'users.id' => 'user_activities.user_id',
            ],
            'select'     => ['user_activities.created_at as activity_time', 'user_activities.type as activity_name'],
            'filterable' => ['activity_time', 'activity_name'],
            'sortable'   => ['activity_time', 'activity_name'],
            'soft_delete'=> ['user_activities']
        ],
        
        'profile' => [
            'rel' => [
                'users.pic_id' => 'user_pictures.id',
            ],
            'select'     => ['user_pictures.path as photo'],
            'filterable' => ['photo'],
            'sortable'   => ['photo'],
            'soft_delete'=> ['user_pictures']
        ],
    ];
    
    public function getModelName(): string 
    {
        return User::class;
    }

    public function getSearchable(): array 
    {
        return ['name', 'email'];
    }
    
    public function getFilterable(): array 
    {
        return ['name', 'email', 'created_at'];
    }
    
    public function getSortable(): array 
    {
        return ['name', 'email', 'created_at'];
    }

    //you can use this method for index api on controller
    //if needed, filter and sort methods call automatically join method.
    
    public function getAll(string $search = null, string $filter = null, string $sort = null, int $perPage = 15)
    {
        return $this->search($search)->filter($filter)->sort($sort)->paginate($perPage);
        
        // if you need join in all results,you can use `join` or `joins` in begin of the query like:
        //return $this->joins(['activities','profile'])->search($search)->filter($filter)->... 
    }
    
    //you can use join method with relation name, without filter or sort method
    public function getProfilePic(int $userId)
    {
        $user = $this->join('profile')->where('users.id',$userId)->first();
        
        return $user?->photo ?? 'path/to/no-profile.png';
    }
    
    //You can use multiple join on relations defied on joinable, without filter or sort method
    public function getUserWithAllRelations(int $userId)
    {
        return $this->joins(['activities','profile'])->find($userId);
    }
}

    public function register():void
    {
        //other bindings ...
        //..
        //.
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }

class UserController extends Controller
{

    private UserRepositoryInterface $repo;
    
    public function __construct(UserRepositoryInterface $userRepo) 
    {
        $this->repo = $userRepo;
    }
    
    public function index(Request $request)
    {
        $users = $this->repo->getAll(
            $request?->search,
            $request?->filter,
            $request?->sort
        );
        
        return response($users);
    }

}