PostRepositoryEloquent.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /*
  3. * This file is part of the Jiannei/lumen-api-starter.
  4. *
  5. * (c) Jiannei <longjian.huang@foxmail.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace App\Repositories\Eloquent;
  11. use App\Contracts\Repositories\PostRepository;
  12. use App\Repositories\Criteria\RequestCriteria;
  13. use App\Repositories\Enums\PermissionEnum;
  14. use App\Repositories\Models\Post;
  15. use App\Repositories\Presenters\PostPresenter;
  16. use Illuminate\Support\Arr;
  17. use Spatie\Permission\Exceptions\UnauthorizedException;
  18. /**
  19. * Class PostRepositoryEloquent.
  20. */
  21. class PostRepositoryEloquent extends BaseRepository implements PostRepository
  22. {
  23. public function model()
  24. {
  25. return Post::class;
  26. }
  27. public function presenter()
  28. {
  29. return PostPresenter::class;
  30. }
  31. public function boot()
  32. {
  33. $this->pushCriteria(app(RequestCriteria::class));
  34. }
  35. public function checkPermission()
  36. {
  37. $authUser = auth('api')->user();
  38. // 登录用户是否有 Posts 数据表操作权限
  39. $permission = PermissionEnum::DATA_POSTS()->name;
  40. if (! $authUser->can($permission)) {
  41. throw UnauthorizedException::forPermissions(Arr::wrap($permission));
  42. }
  43. }
  44. public function searchPage()
  45. {
  46. // 使用预加载,避免 N+1
  47. $posts = $this->model->with('author')->published()->paginate(10);
  48. return $this->parserResult($posts);
  49. }
  50. }