I'm fetching data to paginate but pagination is not working, the fetch response is added below, if I return the query relation it retrieves correct data but when I pass it to the custom response function it fetch data only but not the pagination links
try {
$type = 'success';
$status_code = 200;
$message = 'Posts data listed.';
$response = PostResource::collection(Post::with(['associate:id,name,avatar', 'comments:id,commenter_id,commentable_id,comment,created_at'])
->latest('posts.created_at')
->paginate(2));
} catch (Exception $e) {
$type = 'error';
$status_code = $e->getCode();
$message = $e->getMessage();
$response = false;
}
return response_data($type, $status_code, $message, $response);
Here is my response_data function code
function response_data($type, $status, $message = false, $response)
{
return response()->json(['type' => $type, 'status' => $status, 'message' => $message, 'response' => $response]);
}
but if return the query directly it retrieves data with pagination
here is my response that retrieved by the collection
{
"type": "success",
"status": 200,
"message": "Posts data listed.",
"response": [
{
"id": 32,
"associate_id": 5,
"title": "Test Title",
"content": "Post descriptuoin",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632472717.Laravel.png",
"created_at": "2 months ago",
"associate": {
"name": "Code Logic Technologies Pvt. Ltd.",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1633002782_logo.png"
},
"comments": [
{
"id": 13,
"commenter_id": "62",
"commentable_id": "32",
"comment": "Nice offer",
"created_at": "2 months ago",
"user": {
"id": 62,
"name": "Rikesh Shakya",
"username": "rikesh-shakya",
"mobile_number": "9823783191",
"email": "skybks5#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-06-11T18:05:07.000000Z",
"updated_at": "2021-06-11T18:05:07.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 16,
"commenter_id": "88",
"commentable_id": "32",
"comment": "tetetete",
"created_at": "2 months ago",
"user": {
"id": 88,
"name": "Neelam Kera",
"username": "neelam-ranjitkar",
"mobile_number": "9860322060",
"email": "shresthaneelam19#gmail.com",
"provider_id": null,
"avatar": "https://oppazz.oppazzgiftcode.com/images/logo.png",
"email_verified_at": null,
"status": "Y",
"created_at": "2021-07-15T14:08:21.000000Z",
"updated_at": "2021-07-15T14:08:21.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
}
],
"associate_social_sites": {
"id": 5,
"associate_id": 5,
"facebook": "https://www.fachook.com",
"instagram": "https://www.instagram.com",
"twitter": "https://www.twitter.com",
"status": "Y",
"created_at": null,
"updated_at": "2021-09-24T09:29:57.000000Z",
"created_by": null,
"updated_by": null,
"device_type": null
}
},
{
"id": 31,
"associate_id": 9,
"title": "OppazZ Coffee For Happiness (Giveaway series)",
"content": "OppazZ",
"image": "https://oppazz.oppazzgiftcode.com/images/posts/1632367205.kamloops-art-page-2.jpg",
"created_at": "2 months ago",
"associate": {
"name": "OppazZ",
"avatar": "https://oppazz.oppazzgiftcode.com/images/associates/1622551849_184399208_2242958835839866_1824735327179728878_n.jpg"
},
"comments": [],
"associate_social_sites": null
}
]
}
how can it be resolved and fetch pagination link along with the data fetched above
The Laravel paginator result classes implement the Illuminate\Contracts\Support\Jsonable interface contract and expose the toJson method, so it's very easy to convert your pagination results to JSON.
You may also convert a paginator instance to JSON by simply returning it from a route or controller action:
https://laravel.com/docs/5.3/pagination#converting-results-to-json
Related
I have some JSON parsing in VBA that's driving me nuts. Here's a sample response:
{
"data": [
{
"type": "access_user",
"attributes": {
"name": "Me",
"email": null,
"phone": null,
"department": "",
"status": "current",
"source": null,
"guest_source": null,
"created_at": "2019-08-19T21:45:56Z",
"updated_at": "2019-08-22T03:38:33Z",
"pin": "77005",
"card_number": null
},
"id": "be66e054-5509-4cf6-a5c2-14b85eb25619",
"links": {
"self": "https://api"
}
},
{
"type": "access_user",
"attributes": {
"name": "Day Code",
"email": null,
"phone": null,
"department": null,
"status": "current",
"source": null,
"guest_source": null,
"created_at": "2019-08-21T19:49:29Z",
"updated_at": "2021-06-16T16:08:28Z",
"pin": "12345",
"card_number": null
},
"id": "3a615a3d-eb1c-4973-9e9f-ace5e29ca964",
"links": {
"self": "https://api"
}
}
],
"meta": {
"page": 1,
"per_page": 25,
"total_count": 2,
"total_pages": 1
}
}
Traversing "data" is fine, but when I traverse "attributes" I'm getting a "Type mismatch" error. Here's my code. I'm not seeing anything wrong. Any thoughts?
For Each Item In Response2.Data("data")
UserType = Item("type")
Id = Item("id")
If UserType = "access_user" Then
For Each Nested In Item("attributes")
Name = Nested("name")
status = Nested("status")
PIN = Nested("pin")
Next
End If
Next
Anyone's assistance is greatly appreciated!
The following two lines are equivalent . . .
For Each Nested In Item("attributes")
and
For Each Nested In Item("attributes").Keys()
So, in fact, you're looping through each key within the dictionary. And so your control variable Nested is assigned a string, hence the type mismatch.
Since Item("attributes") returns a dictionary object, you can eliminate the For Each/Next loop, and you can access your items as follows . . .
Name = Item("attributes")("name")
Status = Item("attributes")("status")
PIN = Item("attributes")("pin")
I am converting a two-dimensional array into a JSON object.
Now my controller returning this output:
[
[
{
"id": 1,
"title": "V1",
"project_id": 1
}
],
[]
]
Want to convert it like:
[
{
"id": 1,
"name": "Laravel"
},
{
"id": 2,
"name": "Wordpress"
}
]
My controller code:
$user = auth()->user();
$projectVersions = array();
foreach($user->projects as $project)
{
$projectId = $project->pivot->project_id;
$projectVersions[] = Version::where('project_id', $projectId)
->where('created_by', $user->id)
->get();
}
return $projectVersions;
When I am using below code which is suggested by #John Lobo, it is returning below output:
{
"id": 2,
"name": "Hadayat Niazi",
"email": "niazicr801#gmail.com",
"is_admin": 0,
"email_verified_at": null,
"created_at": "2021-06-11T15:13:00.000000Z",
"updated_at": "2021-06-11T15:13:00.000000Z",
"projects": [
{
"id": 1,
"name": "Laravel",
"pivot": {
"user_id": 2,
"project_id": 1
},
"versions": [
{
"id": 1,
"title": "V1"
}
]
}
]
}
Displaying the user projects and versions:
Again I am updating the code for #John Lobo, he want to look the output
$user = User::with(['projects', 'projects.versions'])
->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return [
$project->versions,
];
});
return $result;
Output the code
[
[
[
{
"id": 1,
"title": "V1",
"project_id": 1,
"version": "1.22",
"created_by": 2,
"is_publish": 0,
"feature": "<b>In this ipdate asdsdasd</b>",
"bug_fix": "<p><b>sdfdffffffffff</b></p>",
"created_at": "2021-06-12T08:08:21.000000Z",
"updated_at": "2021-06-12T08:08:21.000000Z"
},
{
"id": 2,
"title": "v2",
"project_id": 1,
"version": "2.12",
"created_by": 2,
"is_publish": 0,
"feature": "adsdasdsadas",
"bug_fix": "sddasdas",
"created_at": null,
"updated_at": null
}
]
],
[
[]
]
]
In controller you can do the following.if you have relation in project model called version
$projectVersions=User::with(['projects','projects.version'])->find(auth()->user()->id);
return $projectVersions->projects;
I believe Project model has below relationship
public function version(){
return $this->hasMany(Version::class);
}
Updated
$user=User::with(['projects','projects.versions'])->find(auth()->user()->id);
$result = $user->projects->map(function ($project) {
return $project->versions;
});
dd($result);
Use like below
$json = json_encode($responseOfController);
echo "<pre>";print_r($json);die;
Update at the end
I have this API for a social media app in iOS builded in Laravel and i've been having problems with the feed section, the Eloquent code for the feed is giving me the wrong id for each posts.
public function feed(){
if (request()->has('page')) {
$pagesize = 20;
$query = Posts::join('clase_user', function ($join) {
$user = JWTAuth::parseToken()->authenticate();
$join->on('clase_user.clase_id', '=', 'posts.clase_id')
->where('clase_user.user_id', '=', $user->id);
})
->with('user')
->skip(((int)request()->get('page') - 1) * $pagesize)
->take($pagesize)->get();
return $query;
}else{
return response()->json(['error' => 'Page not specified'], 500);
}
}
the return is this:
{
"posts": [
{
"id": 3,
"user_id": 1,
"clase_id": 1,
"thumbNail": null,
"text": "Hola Chicos",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
},
{
"id": 1,
"user_id": 1,
"clase_id": 2,
"thumbNail": null,
"text": "Que pex Prrrro",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
},
{
"id": 3,
"user_id": 1,
"clase_id": 1,
"thumbNail": null,
"text": "Que Onda Chicos",
"archivo": null,
"created_at": "2017-07-20 00:00:00",
"updated_at": "2017-07-20 00:00:00",
"user": {
"id": 1,
"name": "Juan Carlos",
"about": "Hola me llamo Juan Carlos",
"handler": "Juantvz50",
"pp": null,
"verify": 1,
"email": "jc_estevezr#hotmail.com",
"deleted_at": null,
"LoginId": null,
"created_at": "2017-07-20 23:52:28",
"updated_at": "2017-07-20 23:52:28"
}
}
]
}
Even though my database has different ids for each one:
Database
it looks like something is wrong in some part of my code, I don't know in which part if you want to see more code just ask in the comments.
UPDATE
the id it's giving me is in fact the id of the table clase_user that is the pivot table I use to join many to many the classes with the users (like when you follow someone on youtube), I think is because i'm saying Posts::join('clase_user', any ideas to also include the the id of the post?
clase_user
Similar to this one: Join with where query in Laravel returns wrong timestamps
Because of your JOIN the attributes are getting overridden (not only the id but also the created_at/updated_at timestamps). Therefore you should define a select statement for your specific attributes.
I'm trying to return json with two classes in my model
public function both()
{
return $this->belongsToMany(Car::class)->and(Driver::class)->withPivot('type'); // this is wrong
}
the reason I'm trying to get this like that is because in my function
public function check()
{
$user = JWTAuth::parseToken()->authenticate();
$id = $user->id;
$result = User::with('both')->where('id', $id)->get();
return response()->json($result);
}
right now in my model I have this
public function both()
{
return $this->belongsToMany(Car::class)->withPivot('type');
}
public function driver()
{
return $this->belongsToMany(Driver::class)->withPivot('type');
}
But the function returns json that has a different structure when both ends.
My question is can I have the function return a json with the same structure?
like this
[
{
"id": 4,
"name": null,
"phone": "9000",
"size_of_house": null,
"created_at": "2016-12-04 13:55:52",
"updated_at": "2017-03-08 14:03:44",
"deleted_at": null,
"both": [
{
"id": 177,
"name": "NIS",
"created_at": "2016-12-27 10:28:29",
"updated_at": "2016-12-27 10:28:29",
"pic": "http://localhost:8000/images/1482833485.jpg",
"pivot": {
"user_id": 4,
"car_id": 177,
"type": "car"
}
},
"both": [
{
"name": "Abdulaziz Alomhsen",
"age": "30",
"created_at": "2017-02-28 09:36:15",
"updated_at": "2017-03-08 08:46:06",
"status": "جايه",
"pic": "http://localhost:8000/images/1488714520.jpg",
"id": 2,
"pivot": {
"user_id": 4,
"driver_id": 2,
"type": "driver"
}
},
How do I use ng-repeat if my JSON looks like
[
{
"id": "1",
"shop_name": "Shop Name",
"user_id": "2",
"shop_email": "",
"shop_address": "",
"shop_phone": "",
"company_name": "",
"description": "",
"shop_provision": null,
"created_at": "2014-11-05 10:32:32",
"updated_at": "2014-11-06 21:02:00",
"banners": [
{
"id": "18",
"disk_name": "545be1dfa2011452107756.png",
"file_name": "Screenshot from 2014-11-06 09:50:48.png",
"file_size": "135441",
"content_type": "image/png",
"title": null,
"description": null,
"field": "banners",
"sort_order": "18",
"created_at": "2014-11-06 21:02:23",
"updated_at": "2014-11-06 21:02:34",
"path": "/uploads/public/545/be1/dfa/545be1dfa2011452107756.png",
"extension": "png"
},
{
"id": "20",
"disk_name": "545be1e6b5048131391528.png",
"file_name": "Screenshot from 2014-11-06 09:50:48.png",
"file_size": "135441",
"content_type": "image/png",
"title": null,
"description": null,
"field": "banners",
"sort_order": "20",
"created_at": "2014-11-06 21:02:30",
"updated_at": "2014-11-06 21:02:34",
"path": "/uploads/public/545/be1/e6b/545be1e6b5048131391528.png",
"extension": "png"
}
]
}
]
on banners I would like iterate again
On controller I get a JSON object or array which contains a subObject (responseJSON)
october.controllers['dashboard/wm'] = function ($scope, $request) {
$scope.banners = $request('onGetBanners'); //the $request is an ajax function
console.log($scope.banners);
}
the subObject
responseJSON looks like as the result in firebug console
Object { result="[{"id":"1","shop_name":"...","extension":"png"}]}]"}
from all this I want the result=
than I try to iterate the scope like
<div ng-repeat="banner in banners.responseJSON.result track by $index"></div>
Update
I changed the way as I initiate the scope in controller
october.controllers['publishers/wm'] = function ($scope, $request) {
$request('onGetBanners', {success: function(data){
this.success(data).done(function() {
$scope.response = data.result;
});
}})
}
than again trying iterate
{% verbatim %}
{{response}} //outputs
[
{
"id": "2",
"shop_name": "Test Shop",
"user_id": "1",
"shop_email": null,
"shop_address": null,
"shop_phone": null,
"company_name": null,
"description": "",
"shop_provision": null,
"created_at": "2014-11-05 11:31:15",
"updated_at": "2014-11-05 11:31:15",
"banners": []
}
]
<div ng-repeat="shop in response track by $index">
{{ shop.shop_name }} //no data
</div>
{% endverbatim %}
if I remove track by $index I get
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: shop in response, Duplicate key: string:", Duplicate value: "\""
Got it and I never gonna forget this pain
angular.fromJson(jsondata)
Have you tried something like this?
HTML
<div ng-repeat="shop in responseJson">
{{shop.id}}
<div ng-repeat="banner in shop.banners">
<img ng-src="{{banner.path}}>
</div>
</div>
See on jsFiddle