Skip to content

Repositories

Zane H edited this page Jun 15, 2021 · 1 revision

Repositories are a wrapper around Eloquent models (Laravel's ORM). First, include the repository in the class you are working in. This usually looks like this:

/**
 * @var ReportRepository
 */
private $reports;

public function __construct(ReportRepository $reports) {
  $this->reports = $reports;
}

Sometimes __construct is swapped for boot if you are extending another class that has a constructor. Laravel automatically instantiates this repository and gives your class an instance of it if your class was created through the dependency injection container, as most class instances are. You can also get an instance of the repository manually via app(ReportRepository::class) if dependency injection isn't an option.

These repositories contain useful methods for querying the database. Calling ->query() on a repository instance will give you back a query builder instance, with which you can use any of Eloquent's query builder syntax, e.g.:

$reports = $this->reports->query()
  ->where('status', 1)
  ->where('some_field', '>', 5)
  ->orderBy('some_field', 'desc')
  ->limit(10)
  ->get()