I have the following simple index method:
public function index()
{
// dd(Poll::paginate(2));
return response()->json(Poll::paginate(2),200);
}
The output of that method is looks like the following json object:
{
"current_page": 1,
"data": [
{
"id": 1,
"title": "I suppose?' said Alice. 'Why, you don't know.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
},
{
"id": 2,
"title": "Alice; but she knew that it seemed quite.",
"created_at": "2018-09-14 16:42:11",
"updated_at": "2018-09-14 16:42:11"
}
],
"first_page_url": "http://127.0.0.1:8000/polls?page=1",
"from": 1,
"last_page": 6,
"last_page_url": "http://127.0.0.1:8000/polls?page=6",
"next_page_url": "http://127.0.0.1:8000/polls?page=2",
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11
}
I want to add another array property after "total: 11" attribute such as:
,
"anotherData" : [
"userId": 1,
"userName": "john10",
"message": "This is a message"
]
I have tried to understand how response()->json() works, so it can extract some data from LengthAwarePaginator object which it is the output of Poll::paginate(2) from this resource, but I could not able to understand how does it able to get an array from LengthAwarePaginator that holds the resultant keys in the json object?!
From the regarded resource above, the json() method takes an array and, I guess that, if the parameter is not an array, it tries to convert it to array, specially if it is an object like LengthAwarePaginator, so it may use toArray() method.
I have tried replacing return response()->json(Poll::paginate(2),200) with return response()->json(Poll::paginate(2)->toArray,200), then I have got the same output. Hence, I have decided to replace the code of my index method to be like the following:
public function index()
{
//dd(Poll::paginate(2)->toArray());
$output = Poll::paginate(2)->toArray();
$output['userData'] = ['userId' => \Auth::user()->id, 'userEmail' => \Auth::user()->email];
return response()->json($output,200);
}
The resultant output is:
...
"path": "http://127.0.0.1:8000/polls",
"per_page": 2,
"prev_page_url": null,
"to": 2,
"total": 11,
"userData": {
"userId": 1,
"userEmail": "lion#example.com"
}
}
If you're directly responding with the paginated data, a better option would be to wrap it in a Resource Collection and adding meta data to it.
This is how I implemented it.
CategoryController.php
public function index()
{
return new CategoryCollection(Category::paginate(10));
}
CategoryCollection.php
public function toArray($request)
{
return [
'status' => 1,
'message' => 'Success',
'data' => $this->collection,
];
}
Since Collection extends JsonResource, your response would automatically be converted to JSON when returned from the Controller.
Related
Hi I got a bit stuck at trying to understand how to fetch data of a JSON file.
environment.ts:
export const environment = {
production: false,
urlListBooks: "/assets/list-books.json",
urlGetBooks: "/assets/edit-book.json?:id",
urlGetTags: "/assets/edit-book.json?:tags",
urlPostBooks: "/assets/edit-book.json",
urlListTags: "/assets/list-tags.json",
urlPostTags: "/assets/edit-tag.json"
};
edit-book.json:
"book":{
"id": 1,
"title": "The Shining",
"authorId": 1,
"tags": [{"name":"new"}, {"name":"test"}]
},
"authors":[
{
"id": 1,
"prename": "Stephen",
"surname": "King"
},
{
"id": 3,
"prename": "Algernon",
"surname": "Blackwood"
},
{
"id": 4,
"prename": "Edgar Allan",
"surname": "Poe"
},
{
"id": 5,
"prename": "Howard Phillips",
"surname": "Lovecraft"
}
],
"tags":[
{
"name": "new"
},
{
"name": "Horror"
},
{
"name": "Romance"
}
]
}
service:
getBookTags(n: String) Observable<Tag[]>{
return this.http.get<Tag[]>(environment.urlGetTags.)
}
what I want getBookTags(n: String) to do is returning the tags array of the book with title n defined in the edit-book.json (e.g. "tags": [{"name":"new"}, {"name":"Horror"}] ) so that I can later use the function to check which tags a book has and select them.
Your help would be very appreciated :)
Ok I think I've solved this for you, I'm going to walk through my process with you so you understand what the goal is. You can see my solution here: https://codesandbox.io/s/thirsty-minsky-g6959f?file=/assets/edit-book.json:0-752
First thing is that your JSON you provided doesn't really make much sense, it shows multiple authors and just one "book". I think instead you want multiple books. Secondly, it's gotta be wrapped in a curly brace as shown:
{
"books": [
{
"id": 1,
"title": "The Shining",
"authorId": 1,
"tags": [{ "name": "new" }, { "name": "test" }]
},
{
"id": 2,
"title": "The Wendigo",
"authorId": 2,
"tags": [{ "name": "Horror" }]
}
],
"authors": [
{
"id": 1,
"prename": "Stephen",
"surname": "King"
},
{
"id": 3,
"prename": "Algernon",
"surname": "Blackwood"
},
{
"id": 4,
"prename": "Edgar Allan",
"surname": "Poe"
},
{
"id": 5,
"prename": "Howard Phillips",
"surname": "Lovecraft"
}
],
"tags": [
{
"name": "new"
},
{
"name": "Horror"
},
{
"name": "Romance"
}
]
}
Now, in your Typescript code we want to have typings for the json you're going to fetch. This will make your code more readable, it will give you intellisense, and help you catch some errors before you try to run your code. So we are going to go ahead and type the properties of the JSON as follows:
type Tag = {
name: string;
};
type Book = {
id: number;
title: string;
authorId: number;
tags: Tag[];
};
type Author = {
id: number;
prename: string;
surname: string;
};
type BookData = {
books: Book[];
authors: Author[];
tags: Tag[];
};
Basically what I said is we have bookdata which is made up of books, authors, and tags. Books have properties given under type Book, same thing with Author and Tag.
Now for the actual running code, we are going to use the fetch api to get the json data at the url.
async function getBookTags(n: string): Promise<Book[]> {
return fetch(url)
.then<BookData>((res) => res.json())
.then((data) => data.books)
.then((books) => books.filter((b) => doesBookHaveTag(b, n)));
}
First thing we do is fetch the data from the api, this returns a promise which when resolved (this is what .then does) we take the response and parse it for a json. Then when that promise resolves we get the books in the data. Then when that promise resolves we filter in books that have the matching tag.
doesBookHaveTag is just a little helper function I defined:
function doesBookHaveTag(book: Book, n: string): boolean {
// just return if book has at least one tag matching n
return book.tags.some((t) => t.name.toLowerCase() === n.toLowerCase());
}
If you don't understand promises you should watch some videos on it, but basically the browser sends out an http request and then when it resolves it queues a task to execute the function [see endnote] in .then when it has time. So when we want to call your async function and say log all books with the tag "horror" we do it as shown:
getBookTags("horror").then(console.log); // returns the one book.
I hope this makes sense and you can sort of see how to fetch the data, how to handle the promise it returns, and how to type your response. The only thing I'm not sure on is how Angular changes this for you (I'm a react guy), but this is really just non-library specific Javascript/Typescript.
[endnote] when I say function in .then, what I mean is that .then(data => data.books) is passing a function into the .then function. data => data.books is actually a function the same as:
function(data: BookData): Book[] {
return data.books
}
I am on Laravel 7.x and I have two models (CustomerOrder composed of many CustomerOrderLines) with parent - child relationship. Parent (CustomerOrder) model has a json type field among its fields.
CustomerOrderResource.php:
return [
'id' => $this->id,
'wfx_oc_no' => $this->wfx_oc_no,
'qty_json' => json_decode($this->qty_json)
];
CustomerOrderLineResource.php:
return [
'id' => $this->id,
'description' => $this->description,
'customer-order' => $this->customerOrder
];
CustomerOrder->GET request returns properly formatted data as:
"data": {
"id": 11,
"wfx_oc_no": 12,
"qty_json": {
"L": "20",
"M": "30",
"S": "20",
"XL": "100"
}
}
But for CustomerOrderLine->GET, the response is as:
"data": {
"id": 15,
"description": "test desc",
"customer-order": {
"id": 11,
"wfx_oc_no": 12,
"qty_json": "{\"L\": \"20\", \"M\": \"30\", \"S\": \"20\", \"XL\": \"100\"}"
}
}
json field is not properly formatted. It seems it doesn't go through Resource class. Please let me know, how can I get this fixed?
FYI
CustomerOrderLine.php:
public function parent()
{
return $this->belongsTo(CustomerOrder::class);
}
Finally managed to get it solved using json cast. The field was included in $casts array in the model.
im working on Laravel Rest Api with passeport ,
in return response()->json() i want to trim the brackets
I've tried trim($json,'[]') function but it's not what i want
public function getOffers()
{
$offers = Offer::where('type', 'primary')->where('active', 1)->get();
$paks = Offer::where('type', 'pack')->where('active', 1)->get();
return response()->json([
'offersList' => $offers,
'packsList' => $paks,
], 200);
}
i expect the output will be
{
"offersList": {
{
"id": 3,
"name": "Gold",
"description": null
}
},
"packsList":[]
}
but the actual result is
{
"offersList": [
{
"id": 3,
"name": "Gold",
"description": null
}
],
"packsList":[]
}
$offers is a collection, and thus an array in JSON.
If $offers should be a single item, use first() instead of get() and it will be rendered as a single object in your JSON instead of an array of objects.
$offers = Offer::where('type', 'primary')->where('active', 1)->first();
If $offers should, at times, contain multiple offers, leave it as-is; it's correct!
Braces {} nested in another object is not valid JSON.
Objects can be used in property values and as array elements.
Not valid JSON
{
"offersList": {
{
"id": 3,
"name": "Gold",
"description": null
}
}
}
Valid option 1
{
"offersList": [
{
"id": 3,
"name": "Gold",
"description": null
}
]
}
Valid option 2
{
"offersList": {
"id": 3,
"name": "Gold",
"description": null
}
}
You can use online linters to quickly validate your JSON structure.
https://jsonformatter.curiousconcept.com/
I have a JSON Response and want to extract list of values from response for e.g all the values of id's present.
{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
{
"id": 4,
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
},
{
"id": 5,
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
},
{
"id": 6,
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
}
]
}
I have tried below code but not able to achieve but it is only printing first value of id i.e 4.
public class Get_Request {
public static void main(String[] args) {
RestAssured.baseURI = "https://reqres.in/";
Response res = given()
.param("page", "2")
.when()
.get("/api/users")
.then()
.assertThat()
.contentType(ContentType.JSON)
.and()
.statusCode(200).extract().response();
/*String data = res.jsonPath().getString("data[0].first_name");
System.out.println(data);
*/
List<HashMap<String,Object>> allids = res.jsonPath().getList("data");
HashMap<String,Object> firstid = allids.get(0);
Object a = firstid.get("id");
System.out.println(a);
}
}
I am beginner in rest assured also i am not sure whether we can achieve the same. Any help would be appreciated. Thanks in advance.
Below Code will find all the ids present in the Response and it will print the result like 4 5 6
List<Integer> ids = res.jsonPath().getList("data.id");
for(Integer i:ids)
{
System.out.println(i);
}
That can be done by changing your path to data.id
List<Integer> ids = res.jsonPath().getList("data.id");
Integer id = ids.get(0);
You can use JsonPath wildcards to extracts data from response , which will save you from writing code everytime you have such requirement, use below JsonPath to extract list of Ids from your response :
$..id
I am getting JSON response like this. But I want to remove "headers", "original" and "exception".
{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}
Output expected:
{
"data": {
"id": 271,
"name": "TestController",
"parent_id": null
},
"errors": [],
"success": true,
"status_code": 200
}
You are returning a response()->json() inside another response()->json() something along the way:
response()->json(response()->json($data,200),200)
or more like:
$data = [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
];
$response = response()->json($data,200);
return response()->json($response ,200);
You may not have notice it because of a function returning the first response()->json() into the second one
You can use this
$json='{
"headers": {},
"original": [
{
"id": 271,
"name": "TestController",
"parent_id": null
}
],
"exception": null
}';
$arr=json_decode($json);
$data=$arr->original[0];
$new_json=array();
$new_json['data']=$data;
$new_json['errors']=[];
$new_json['success']=true;
$new_json['status_code']=200;
$new_json=json_encode($new_json);
You may have doubled the data json return with response()->json()
you can use array only
return ["data"=> [
"id"=> 271,
"name"=> "TestController",
"parent_id"=> null
],
"errors"=> [],
"success"=> true,
"status_code"=> 200
];
In my case this problem solved with this solution:
You can use:
return json_decode(json_encode($ResponseData), true);
And return response
This is what I did, and it worked for me:
just call the original object after getting your response like this:
public function user_object(){
return $this->me()->original;
}
This is the me() function that returns user details
public function me()
{
return response()->json(auth('users')->user()->only(['id','name','email','status','phonenumber','type']));
}
This is my response from post man:
{
"success": true,
"user": {
"id": 29,
"name": "test6",
"email": "test6#gmail.com",
"status": 1,
"phonenumber": "413678675",
"type": "user"
},
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC8xMjcuMC4wLjE6ODAwMFwvYXBpXC9hdXRoXC9yZWdpc3RlciIsImlhdCI6MTU5OTQ3MDc3OCwiZXhwIjoxNTk5NDc0Mzc4LCJuYmYiOjE1OTk0NzA3NzgsImp0aSI6InFyUWEyTVNLVzR4a2o0ZVgiLCJzdWIiOjI5LCJwcnYiOiI4N2UwYWYxZWY5ZmQxNTgxMmZkZWM5NzE1M2ExNGUwYjA0NzU0NmFhIn0.SMHgYkz4B4BSn-fvUqJGfsgqHc_r0kMDqK1-y9-wLZI",
"expires_in": 3600
}
The issue is triggered because you are returning nested responses somewhere in your code.
Here is a simple code that demonstrates the issue and the fix.
// A normal function that you think it returns an array
// but instead, it is returning a response object!
public function get_data(){
//ISSUE
return response([1, 2, 3]); // <- this will trigger the issue becuase
// it returns the data as a response not an array
//FIX
return [1, 2, 3]; // <- this will work as intended
// bacause the data is returned as a normal array
}
public function get_all_data(){
$first_array = [1, 2];
$second_array = [2, 3];
$third_array = get_data(); // <- here is the call to the function
// that should return an array
//Return the JSON response
return response([first_array, second_array, third_array]);
}