Laravel Repositories

前端 未结 4 2129
野趣味
野趣味 2020-12-09 03:27

What are the advantages of Repositories in Laravel? It seems to be abstracting the Model layer from the business logic of the application. Although it really just seems to m

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 04:08

    In addition to the other answers here, it's worth pointing out that repositories used when used in Laravel can add an extra level of expressiveness. Take for example the following:

    $users = User::whereHas("role", function($q) {
        $q->where('name', 'moderator');
    }, '<', 1)->get();
    

    The code is difficult to read and awkward to look at. It can be encapsulated in a repository method, and demonstrate much clearer code intent:

    $users = $userRepository->getUsersWhoAreNotModerators();
    

    This is also achievable using eloquent 'query scopes' but I think using a repository is superior, as is adheres much better to the single responsibility principal, and is doable regardless of whether you are using Eloquent.

提交回复
热议问题