laravelrepository-patternlaravel-5.8

How to use laravel repository pattern searchable array?


I am using laravel-repository pattern ,i have one api which is responsible for getting all users it's working fine ,if we are using that package by default search should support for that i set $fieldSearchable array in the repository class.

i hit an api like this localhost.com/api/lists?search=foo,it's not working can you please help me where did i mistake

UserController.php

public function __construct(UserRepositoryInterface $repository)
    {
        $this->repository = $repository;
    }
 public function getUsers(){
        $data = $this->repository->show();
        return response()->json(fractal($data, new UserTransformer()));
    }

UserRepositoryInterface.php

interface UserRepositoryInterface extends RepositoryInterface
{
    public function show();
}

UserRepository.php

<?php

namespace App\Repositories;

use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\User as AppUser;
use App\UserSection;
use App\Validators\UserValidator;
use Illuminate\Support\Facades\DB;

/**
 * Class UserRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class UserRepository extends BaseRepository implements UserRepositoryInterface
{

  protected $fieldSearchable = ['phone_number'];
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return AppUser::class;
    }

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

  

    public function show(){
      return $this->model()::get();
    }
    
}



Solution

  • It maybe resolved by utilising pre-defined methods No need to write show() function logic because by default l5-Repository pattern contains some methods to get all the data all() or paginate().

    In your controller write your code like this in getUsers():

    $data = $this->repository->all();
    or
    $data = $this->repository->paginate('25');
    

    all() is for fetching all the data from the database, and paginate($limit) is fetch the data per page based on the limit.

    If you are using any one of the above mentioned method then automatically search functionality will work