jagdishabhiandroid
1 year ago

Edit API response

Posted 1 year ago by jagdishabhiandroid

i want to change my Api response without losing pagination and meta feature here is my code which am using right now

<?php 
public function seefav(Request $request)
    {
      
      
      //echo $request->student_id;
      
      $validator = \Validator::make($request->all(), [
        'student_id'=> 'required',
             ]);
         if ($validator->fails()) {
            
            return Response::json(['message' => 'Empty values not allowed']);
        }else{
            
            
      if (favourites::where('student_id', $request->student_id)->exists()) {
          
          
          
        $student = favourites::where('student_id', $request->student_id)->paginate(20);
        //print_r($student);
         // Return single list as a resource
        foreach($student as $st){ 
            $quiz=$st->quiz_id;
            
            
        }
       
        $resultsquiz = DB::select( DB::raw("SELECT * FROM quizzes WHERE quiz_id ='$quiz'") );
  foreach($resultsquiz as $resquiz){
      $id=$resquiz->id;
      $quiz_image=asset($resquiz->quiz_image);
       $quiz_time=$resquiz->question_time;
       $life=$resquiz->life;
       $quiz_best=$resquiz->best_score;
       $quiz_name=$resquiz->quiz_name;
       
       
       
  }
  
  
       
       
        //return FavouritesResource::collection($student);
       return FavouritesResource::collection($student)->additional([
            'data' => [
                'id'=>$id,
                'quiz_name' => $quiz_name
            ]
        ]); 
       
        
        
      }else{
      return Response::json(['message' => 'NO data found ']); 
    }
    
        }
} ```

i want to change my response to 

```{
  "data": {
    "0": {
      "id": 2,
      "quiz_name": "sumit",
      "quiz_image": "http://mobileappdatabase.in/quiz/",
      "quiz_id": "quiz_id_5b35bbb663bd0",
      "student_id": "SID31867"
    },
    "id": "1",
    "quiz_name": "Demo"
  },
  "links": {
    "first": "?page=1",
    "last": "?page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "",
    "per_page": 20,
    "to": 1,
    "total": 1
  }
}````

this to this 


```{
  "data": {
    "0": {
      "id": 2,
      "quiz_name": "sumit",
      "quiz_image": "http://mobileappdatabase.in/quiz/",
      "quiz_id": "quiz_id_5b35bbb663bd0",
      "student_id": "SID31867",
      "quiz_name": "Demo"
    },
   
  },
  "links": {
    "first": "page=1",
    "last": "page=1",
    "prev": null,
    "next": null
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 1,
    "path": "",
    "per_page": 20,
    "to": 1,
    "total": 1
  }
}```

Please sign in or create an account to participate in this conversation.