Skip to content

Instantly share code, notes, and snippets.

@JustSteveKing
Created August 7, 2021 06:57
Show Gist options
  • Save JustSteveKing/4cd893436c7629993266921fb24e3da4 to your computer and use it in GitHub Desktop.
Save JustSteveKing/4cd893436c7629993266921fb24e3da4 to your computer and use it in GitHub Desktop.
An example on Laravel Eloquent Repository
<?php
abstract class Repository
{
protected Builder $query;
public function all(): null|Collection
{
return $this->query->get();
}
}
class UserRepository extends Repository
{
public function __construct(string $model)
{
$this->query = $model->query();
}
}
@JustSteveKing
Copy link
Author

Service Provider:

class RepositoryServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->bind(UserRepository::class, new UserRepository(model: App\Models\User::class,),);
    }
}

@harmlessprince
Copy link

So for every model, I will come here to resister the repository ?

@JustSteveKing
Copy link
Author

Controller:

class UserController extends Controller
{
    public function __construct(
        protected UserRepository $repository,
    ) { }

    public function index(): Response
    {
        return $this->repository->all();
    }
}

@JustSteveKing
Copy link
Author

So for every model, I will come here to resister the repository ?

Yep! That's the best way to do it

@harmlessprince
Copy link

oh well, Let me get to work.

Thank you very much Steve.

@harmlessprince
Copy link

Screenshot from 2021-08-08 09-00-47
I am getting this error, while trying to run "composer-dump autoload"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment