returning response with json in laravel api removes the collection pagination links - laravel

i'm using laravel for webservice. i want to return a collection like this:
return response()->json([data => $data]);
and i'm using laravel api resouces for transforming the collection. this is my resource:
class Item extends JsonResource
public function toArray($request)
{
return [
'id' => $this->id,
'name'=> $this->name,
'city_dependent' => $this->city_dependent,
];
}
when i pass a collection to the resource like:
$items = Item::where('active' , 1)->paginate(10);
$data = Item::collection($items);
everything works good. if i return the $data, the pagination links and meta are returning and there is no problem.
"links": {
"first": "http://127.0.0.1:8000/api/category/items?page=1",
"last": "http://127.0.0.1:8000/api/category/items?page=1",
"prev": null,
"next": null
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 1,
"path": "http://127.0.0.1:8000/api/category/items",
"per_page": 10,
"to": 3,
"total": 3
}
but if i return the data with response()->json() like below, all data about "meta" and "links" are remove! and everything else is ok.
return response()->json([
'result' =>true,
'data' => $data
]);
why the pagination data and links are removed from the data? is there anything that i missed?

Related

How to pull actual values from foreign id when an array of ids is returned?

I am making an e-commerce site where the person can make an offer for the product. And I want to display all the offers on product at a place where I get the product.After that want to get the information about the user who made the offer and the parent offer in the same query.
I am getting the product like this
`public function show(Product $product)
{
// return response()->json($product);
return new SingleProductResource($product);
}`
The SingleProductResource returns the following
`public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'type' => $this->type,
'images' => $this->images,
'status' => $this->status,
'owner' => $this->user,
'offers' => $this->offers,
];
}`
Offers returns an array like this
`"offers": [
{
"id": 2,
"user_id": null,
"product_id": 1,
"offer_amount": "3",
"parent_id": 2,
"created_at": "2022-11-12T07:54:10.000000Z",
"updated_at": "2022-11-12T07:54:10.000000Z"
},
{
"id": 4,
"user_id": 1,
"product_id": 1,
"offer_amount": "3",
"parent_id": 2,
"created_at": "2022-11-12T08:01:29.000000Z",
"updated_at": "2022-11-12T08:01:29.000000Z"
},
{
"id": 5,
"user_id": null,
"product_id": 1,
"offer_amount": "3",
"parent_id": null,
"created_at": "2022-11-12T08:01:56.000000Z",
"updated_at": "2022-11-12T08:01:56.000000Z"
}
]`
But I want to get the user information directly in this query.
I cannot do this(see comment below) inside the resource as $this->offers returns an array.
`return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'type' => $this->type,
'images' => $this->images,
'status' => $this->status,
'creator' => $this->user,
'offers' => $this->offers->user, //this
];`
You will need to trim your $product in some way. For example
$products = Product::leftJoin('offers', 'products.id', 'offers.product_id')
->where('user_id')
->where('products.id', $product['id'])
->get();
return new SingleProductResource::collection($products);

How can I add pagination in Lumen 8 collection?

I am using Lumen to create api where I integrate collection. All code details are given below. I want to add pagination according to my code. How I add paginator in my code?
In Controller:
//To get all Employee Type
public function getAllEmployeeTypes(){
$employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->get();
return new OsEmployeeTypeCollection($employeeType);
}
In Collection it looks like
public function toArray($request)
{
return [
'data' => $this->collection->map(function($data) {
return [
'id' => $data->id,
'name' => $data->name,
'priority' => $data->priority,
'status' => $data->status,
];
})
];
}
public function with($request)
{
return [
'success' => true,
'status' => 200
];
}
and the response that I got
{
"data": [
{
"id": 3,
"name": "Type 3",
"priority": 3,
"status": 1
},
{
"id": 2,
"name": "Type 2",
"priority": 2,
"status": 1
},
{
"id": 1,
"name": "Type 1",
"priority": 1,
"status": 1
}
],
"success": true,
"status": 200
}
How can I paginate my API response?
Paginate is the same as Laravel in Lumen. You will do just the same as in Laravel.
$employeeType = OsEmployeeType::where('status',1)->orderBy('priority', 'DESC')->skip(10)->take(5)->get();

Laravel 8 - Get value from api json response

I am trying to get the value from 'title' in an API JSON response in Laravel 8.
{
"kind": "search#companies",
"page_number": 1,
"items_per_page": 20,
"total_results": 1,
"items": [
{
"kind": "searchresults#company",
"links": {
"self": "/company/13082103"
},
"title": "BITPIX LIMITED",
}
],
"start_index": 0
}
The call is setup and it works as expected but I am unsure how to get the variable.
The call will only ever return 1 response within items[] as the search is based on id.
Here is my method
$company = Auth::user()->companies()->first();
$apiKey = env("COMPANIES_HOUSE");
$query = $request->validate([
'query' => 'required',
]);
$response = Http::withHeaders([
'Authorization' => 'Basic ' . $apiKey,
'Connection' => 'keep-alive',
'Accept-Encoding' => 'gzip, deflate, br',
'Accept' => '*/*'
])->get('https://api.companieshouse.gov.uk/search/companies?q=' . $query['query']);
$data = json_decode($response->body());
//dd($data);
$provider = $company->providers()->create([
'name' => $data['items'][0]->title
]);
which produces this error:
Cannot use object of type stdClass as array relating to the ->create line
Many thanks for any help you can provide.
you have to decode the json you have recieved then extract the data you want:
$value = '{ "kind": "search#companies", "page_number": 1, "items_per_page": 20, "total_results": 1, "items": [{ "kind": "searchresults#company", "links": { "self": "/company/13082103" }, "title": "BITPIX LIMITED" }], "start_index": 0 }';
$decodeValue = json_decode($value);
$firstTitle = $decodeValue->items[0]->title; // first title is BITPIX LIMITED

return user model with eager loading laravel

return $data =InteractiveSession::with('messages.user')->where('exercise_id',$exercise->id)->first();
This code will return data like below
{
"id": 1,
"exercise_id": 48,
"messages": [
{
"id": 1,
"from_user": 69,
"message": "Hi",
"interactive_session_id": 1,
"user": {
"id": 69,
"first_name": "Jobin"
}
}
]}
how can i return data like below??
{
"id": 1,
"exercise_id": 48,
"messages": [
{
"id": 1,
"from_user":{
"id": 69,
"first_name": "Jobin"
},
"message": "Hi",
"interactive_session_id": 1,
}
]}
i have tables interactivesession,message,users, using hasmany relation
You can create a relation for from_user to the user model, and then do return $data = InteractiveSession::with(['messages.user', 'fromUser'])->where('exercise_id',$exercise->id)->first(); (remember fromUser should be your relation name)
Try this:
$data = InteractiveSession::with('messages.user')->where('exercise_id',$exercise->id)->first();
$data->transform(function($record) {
$messages = $record->messages->transform(function($message) {
'id' => $message->id,
'from_user' => [
'id' => $message->user->id,
'first_name' => $message->user->first_name
],
'message' => $message->message,
'interactive_session_id' => $message->interactive_session_id
});
return [
'id' => $record->id,
'exercise_id' => $record->exercise_id,
'messages' => $messages
];
});

Laravel API Resource Collection return specific fields from other resource

I am working on an api that will be accessible via a mobile app.
I have defined resources and collections for respective endpoints. My problem is now is that I want to return different api json data based on what ever collection.
Here is an example
Provinces has cities and suburbs, so in json format I need to have
"data": [
{
"id": 1,
"name": "Eastern Cape",
"cities": [
{
"name": "Alice"
},
],
"suburbs": [
"name": "Suburb 1"
]
},
]
I want different data when the cities resource is called in news api collection
"data": [
{
"id": 1,
"name": "Eastern Cape",
"cities": [
{
"name": "Alice",
"municipality": "municipality name",
},
],
"suburbs": [
"name": "Suburb 1",
"ward_number": "ward 1"
]
},
]
This is an NewsResource Api
public function toArray($request)
{
// return parent::toArray($request);
return [
'id'=> $this->id,
'title' => $this->title,
'slug' => $this->slug,
'content' => $this->content,
'created_at' => $this->created_at,
'category_id' => $this->news_category_id,
'featured_image' => url($this->featured_image),
'author' => new UserResource($this->user),
'category' => new NewsCategoryResource($this->category), //Only category Name to be displayed
'municipality' => new MunicipalityResource($this->municipality), // Only Municipality Name to be displayed
'comments' => new NewsCommentResource($this->comments),
];
}
I don't really know what is your code structure, but hope this help for you
You may use different queries, for example
/** For the obvious resource calling */
return SomeResource::collection (SomeModel::with(['suburbs', 'cities'])
/** Other filter queries */
->get());
/** For the cities resource calling */
return SomeResource::collection (SomeModel::with(['suburbs:id,ward_number', 'cities:id,municipality'])
/** Other filter queries */
->get());
In your Resource class which you use for the cities/suburbs data, do it like so
return [
/** Some data which you need */
'municipality' => $this->when($this->municipality !== null, $this->municipality),
'ward_number' => $this->when($this->ward_number !== null, $this->ward_number),
];

Resources