在Api Lravel中限制请求中的数据

时间:2017-03-21 01:08:56

标签: laravel rest api request vue.js

我在laravel 5.4中有一个API,并使用Vue Resource来使用这个后端。但是在提出请求时,我会带来数据库中的所有信息,这些信息大约是10k。我会将此限制为例如100个问题并提出下一个请求。

我的api存储库

    class QuestionRepository implements QuestionRepositoryInterface
    {

        protected $question;

        public function __construct(Question $question)
        {
            $this->question = $question;
        }

        public function all(){
            $data = $this->question->all();

            return $data;
        }

        public function find($id)
        {
            return $this->question->find($id);
        }

        public function findByTopic($id)
        {
            $questions = $this->question->where('topic_idtopic', '=', $id)->get();

            return $questions;
        }
    public function findBySubject($id)
    {
        $questions = $this->question->where('subject_idsubject', '=', $id)->get();

        return $questions;
    }
}

我的Vue代码

mounted(){

    this.$http.get(window.api+'subject').then((response) => {
        this.subjects = response.data
    });

    this.$http.get(window.api+'questions/count').then((response) => {
        this.count = response.body
    });

    this.status = 1
},

我的问题控制器

   //Todas as questões
    public function index()
    {
        $questions = $this->questionRepository->all();

        return Response::json([
            'questions' => $this->questionTransformer->transformCollection($questions->all())
        ]);
    }

    public function count()
    {
        $count = $this->questionRepository->all()->count();

        return Response::json($count);
    }

    public function show($id)
    {
        $questions = $this->questionRepository->find($id);

        if(!$questions)  return $this->responseNotFound('Question doesn\'t exist');

        return Response::json([
            'questions' => $this->questionTransformer->transformCollection($questions->all())
        ]);
    }
    public function showBySubject($id)
    {
        $questions = $this->questionRepository->findBySubject($id);

        return Response::json([
            'questions' => $this->questionTransformer->transformCollection($questions->all())
        ]);
    }

1 个答案:

答案 0 :(得分:1)

使用分页。更改all()功能或创建新功能。

public function pagination($limit = 100){
    $data = $this->question->paginate($limit);
    return $data;
}

更多信息:https://laravel.com/docs/5.4/pagination