Robię projekt z wykorzystaniem Laravela 5.8.
Mam następujący kod:
1.BaseRepository:
abstract class BaseRepository implements RepositoryInterface { protected $model; public function getAll(string $order = 'id', string $by = 'desc') { return $this->model->orderBy($order, $by)->get()->appends(request()->query()); } public function getAllWithPaginate(string $order = 'id', string $by = 'desc', int $perPage = 1) { return $this->model->orderBy($order, $by)->paginate($perPage)->appends(request()->query()); } public function with($relations) { return $this->model->with($relations); } { return $this->model->create($data); } { $model = $this->model->create($data); return $model->id; } { return $this->model->where("id", "=", $id)->update($data); } public function delete(int $id) { return $this->model->destroy($id); } public function find(int $id, string $order, string $by) { return $this->model->find($id)->orderBy($order, $by); } public function findOrFail(int $id, string $order, string $by) { return $this->model->findOrFail($id)->orderBy($order, $by); } public function getModel() { return $this->model; } }
2. RepositoryInterface:
interface RepositoryInterface { public function getAll(string $order, string $by); public function getAllWithPaginate(string $order, string $by, int $perPage); public function delete(int $id); public function find(int $id, string $order, string $by); public function findOrFail(int $id, string $order, string $by); public function getModel(); }
3 AdRepository:
class AdRepository extends BaseRepository { public function __construct(Ad $model) { $this->model = $model; } public function search(string $query, string $order = 'id', string $by = 'desc', int $perPage = 1) { return $this->model->where('title', 'LIKE', '%' . $query . '%')->orWhere('id', 'LIKE', '%' . $query . '%')->orWhere('content', 'LIKE', '%' . $query . '%')->orderBy($order, $by)->paginate($perPage)->appends(request()->query()); } }
4. Controller:
use App\Models\Ad; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Repositories\AdRepository; public function index(Request $request) { if($request->input('query') != ""){ $adsList = $this->repository->with('author')->search($request->input('query')); } else{ $adsList = $this->repository->with('author')->getAllWithPaginate(); } return view('modules.ad.ad_list', ['adsList' => $adsList]); } protected $model; public function __construct(AdRepository $repository) { $this->model = $repository; }
Kiedy uruchamiam mój kod, otrzymuję błąd:
Call to undefined method Illuminate\Database\Eloquent\Builder::getAllWithPaginate()
W jaki sposób mogę to naprawić?