I’ve to modify an external project written with Laravel.
In brief, I’ve found this BookController.php
class BookController extends AppBaseController
{
public function __construct(BookRepository $brepo)
{
$this->bookRepository = $brepo;
}
public function index(Request $request)
{
$books = $this->bookRepository->paginate(25, ['*'], 'idBook');
[ ... ]
return view('book.index')
->with('book', $book) ;
}
As first step, i want to execute a where filter in the query before pagination, but:
$this->bookRepository->query('author','like','%Joe%');
$this->bookRepository->all([ ??? ], $skip, $limit);
$uselessString = $this->bookRepository->model();
appear to be invalid.
As final step, I want to add in my index.blade.php, the html input element in such a way, I receive it in the $request parameter..
I’ve try to modify the code, but I’ve never used Laravel/Eloquent before..
user is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Here is the structure of the BookRepository class which will work as expected:
class BookRepository {
protected $queryBuilder;
public function __construct() {
$this->queryBuilder = Book::query(); // Initialize with the Book model query
}
public function query($field, $operator, $value) {
$this->queryBuilder->where($field, $operator, $value);
return $this; // Return self for method chaining
}
public function all(array $columns = ['*'], $skip = 0, $limit = 10) {
return $this->queryBuilder->skip($skip)->take($limit)->get($columns);
}
public function reset() {
$this->queryBuilder = Book::query(); // Reset the query builder
}
}
The query method returns $this, allows you to chain additional query methods if needed.
Consider adding a reset method to clear any previous query conditions if you want to start fresh.
You could also use laravel’s built in paginate method for automatic handling of pagination, which simplifies the process significantly.
$limit = 10;
$books = $this->bookRepository->query('author', 'like', '%Joe%')->paginate($limit);
Laravel automatically determines the current page based on the page query parameter in the URL.
4