I'm a laravel beginner and want to build an API with laravel 8.
I have a nested comment and replies system for my posts
and the relation between comments and posts are polymorphic
i want to show a post and comments and replies as JSON
but i don't know my query is correct or not , because i can't understand relation between comments and replies and i just can see all comments and replies related to the post.
this is the JSON response in postman :
[
{
"id": 45,
"category_id": 11,
"user_id": 1,
"title": "title example",
"body": "body example",
"video": null,
"study_time": "8",
"likes": null,
"status": null,
"tags": [],
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:09:14.000000Z",
"updated_at": "2021-05-01T14:09:14.000000Z",
"comments": [
{
"id": 13,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": null,
"name": "sara",
"email": "sara#gmail",
"comment": "its good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:14.000000Z",
"updated_at": "2021-05-01T14:10:14.000000Z"
},
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z"
},
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z"
}
],
}
]
as you see , the replies aren't in array and it's not clear which is a replay and which is a comment
so this is my PostDetailsController :
class PostDetailsController extends Controller
{
/**
* Disply post and comments with replies
**/
public function showPost($id){
$postFind = Post::find($id);
if(is_null($postFind)){
return response()->json('not found' , 404);
}
$post = Post::with('comments')->find($id);
return response()->json([$post] , 200);
}
about comments :
comments table :
chema::create('comments', function (Blueprint $table) {
$table->id();
$table->integer('commentable_id');
$table->string('commentable_type');
$table->unsignedBigInteger('parent_id')->nullable(); //nullable for comments , with value for replies
$table->string('name' , 45);
$table->string('email');
$table->longText('comment');
$table->foreign('parent_id')->references('id')->on('comments')->onUpdate('cascade')->onDelete('cascade');
$table->rememberToken();
$table->softDeletes();
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP'));
});
}
so if parent_id is NULL it's a comment and if has values ( id of parent comments ) it's a reply. (and reply of reply has previous reply id as parent_id )
and the models :
Post :
class Post extends Model
{
protected $fillable = [
'user_id' ,
'category_id' ,
'title' ,
'body' ,
'study_time',
'status',
'tags',
];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable' );
}
}
Comment :
class Comment extends Model
{
protected $fillable = [
'parent_id' , 'name' , 'email' , 'comment' , 'status' , 'images'
];
use HasFactory;
public function commentable(){
return $this->morphTo();
}
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
so can you please tell me is my query wrong?
and what should i do for show replies in an array ?
EDIT
i changed my code to this :
class PostDetailsController extends Controller
{
/**
* Disply post and comments with replies
**/
public function showPost($id){
$postFind = Post::find($id);
if(is_null($postFind)){
return response()->json('not found' , 404);
}
$post = Post::with('comments.replies')->find($id);
return response()->json([$post] , 200);
}
and the response is :
[
{
"id": 45,
"category_id": 11,
"user_id": 1,
"title": "title example",
"body": "body example",
"video": null,
"study_time": "8",
"likes": null,
"status": null,
"tags": [],
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:09:14.000000Z",
"updated_at": "2021-05-01T14:09:14.000000Z",
"comments": [
{
"id": 13,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": null,
"name": "sara",
"email": "sara#gmail",
"comment": "its good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:14.000000Z",
"updated_at": "2021-05-01T14:10:14.000000Z",
"replies": [
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z"
}
]
},
{
"id": 14,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 13,
"name": "john",
"email": "john#gmail.com",
"comment": "its not good",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:10:50.000000Z",
"updated_at": "2021-05-01T14:10:50.000000Z",
"replies": [
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z"
}
]
},
{
"id": 15,
"commentable_id": 45,
"commentable_type": "App\\Models\\Post",
"parent_id": 14,
"name": "sara",
"email": "sara#gmail.com",
"comment": "why?",
"images": null,
"like": null,
"dislike": null,
"status": null,
"remember_token": null,
"deleted_at": null,
"created_at": "2021-05-01T14:11:12.000000Z",
"updated_at": "2021-05-01T14:11:12.000000Z",
"replies": []
}
],
}
]
so i can see the replies of every comment or reply in the response , but as you see the replies are repeated and the last reply that has no reply ,has "replies[]"
What should I do to not show the replay again?
So a couple things here that you could do, firstly your replies have the commentable_type and commentable_id whereas these should probably be nullable since when looking at replies you only really need to know its parent and not the post as you can get this through the parent.
This then allows your $post->comments relationship to not return replies to comments.
Next you can use dot notation to add replies to your comments.
$post = Post::with('comments.replies')->find($id);
This would then return something like this
[
{
"id": 1,
"title": "Title",
"body": "Body",
"created_at": "2021-05-01T11:34:27.000000Z",
"updated_at": "2021-05-01T11:34:28.000000Z",
"comments": [
{
"id": 1,
"post_id": 1,
"parent_id": null,
"body": "No Replies",
"created_at": "2021-05-01T11:34:41.000000Z",
"updated_at": "2021-05-01T11:34:43.000000Z",
"replies": []
},
{
"id": 2,
"post_id": 1,
"parent_id": null,
"body": "One Reply",
"created_at": "2021-05-01T11:35:18.000000Z",
"updated_at": "2021-05-01T11:35:19.000000Z",
"replies": [
{
"id": 3,
"post_id": null,
"parent_id": 2,
"body": "Reply",
"created_at": "2021-05-01T11:35:29.000000Z",
"updated_at": "2021-05-01T11:35:32.000000Z"
}
]
}
]
}
]
Related
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
i have a json data, i want to display it in my flutter app ,so how can i display data from [bookings] partie,for now its easy i use this data[0]['now']['location'], but i have a difficulty to find a way to display data from booking. can someone help me plz
[
{
"now":{
"id": 28,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 4,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 12:30:00",
"date": "2021-12-18",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T14:26:16.000000Z",
"updated_at": "2021-11-10T15:02:33.000000Z",
"location": "",
"duration": 30,
"start": "12:30",
"end": "13:00"
}
},
[
"bookings",
[
{
"id": 29,
"userId": 6,
"bookingTypeId": 1,
"carWasherId": 26,
"buildingId": 2,
"serviceId": 1,
"packageId": null,
"vehiculeId": 2,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-18 09:47:33",
"date": "2021-12-18",
"address": null,
"longitude": null,
"latitude": null,
"rate": null,
"created_at": "2021-10-29T15:03:14.000000Z",
"updated_at": "2021-11-10T15:00:25.000000Z",
"location": "",
"duration": 20,
"start": "09:47",
"end": "10:07"
},
{
"id": 30,
"userId": 6,
"bookingTypeId": 2,
"carWasherId": 26,
"buildingId": 3,
"serviceId": 1,
"packageId": 1,
"vehiculeId": 7,
"tookenPackageId": null,
"status": "ACCEPTED",
"dateTime": "2021-12-22 21:30:00",
"date": "2021-12-22",
"address": null,
"longitude": -6.7436544,
"latitude": 33.9968,
"rate": null,
"created_at": "2021-10-29T15:18:45.000000Z",
"updated_at": "2021-11-10T22:16:47.000000Z",
"location": "",
"duration": 25,
"start": "21:30",
"end": "21:55"
}
]
]
]
Create a named constructor fromJson which accepts your json data and returns a list of Books (see here: https://docs.flutter.dev/development/data-and-backend/json)
class Book{
final String name;
final String id;
User(this.name, this.id);
User.fromJson(Map<String, dynamic> json)
: name = json['name'],
id= json['id'];
Map<String, dynamic> toJson() => {
'name': name,
'id': id,
};
}
First, you create a model of your object. and create JSON file and put it in your project.
String productData = await DefaultAssetBundle.of(context).loadString("assets/product.json");
final jsonResult = jsonDecode(productData);
You can get hear your JSON data and after that, you can initialise your JSON data to the model. like this
var objProductDetails = ProductDetailsDataModel.fromJson(jsonResult);
I am working on jmeter and trying to get values from a Json response.
I have below Json:
`{
"linked": {},
"learning_items": [
{
"id": "3452",
"enrollable_id": "3452",
"enrollable_type": "Enrollment",
"learnable_id": "6",
"learnable_type": "CourseTemplate",
"title": "all kinda ",
"description": "",
"state": "created",
"completed_at": null,
"created_at": "2017-04-10T16:26:36.850-06:00",
"archived_at": null,
"permanently_failed": false,
"data": {
"end_at": "2017-04-16T23:59:59.000-06:00",
"expires_at": null,
"renew_by": null,
"required": true,
"score": 0,
"time_remaining": 5,
"current_position": 0,
"furthest_progress": 0,
"quiz_positions": [
2,
3,
4,
5
],
"direct_enrollment": true,
"max_quiz_attempts": null,
"attempts_count": 0,
"inactive": null,
"program": null,
"programs": [],
"in_completed_program": false,
"external_id": null,
"estimated_time": 5,
"passing_threshold": 80,
"has_certificate": false,
"course_type": "bridge",
"slide_count": 5,
"attachments_count": 1,
"attachments_count_author": 2,
"third_party_course_id": null,
"open_book": true,
"continuing_education_credits": null,
"features": [
"has_quizzes"
]
},
"tags": []
},
{
"id": "3451",
"enrollable_id": "3451",
"enrollable_type": "Enrollment",
"learnable_id": "7",
"learnable_type": "CourseTemplate",
"title": "All types",
"description": "",
"state": "active",
"completed_at": null,
"created_at": "2017-04-10T16:26:36.605-06:00",
"archived_at": null,
"permanently_failed": false,
"data": {
"end_at": "2017-04-17T23:59:59.000-06:00",
"expires_at": null,
"renew_by": null,
"required": true,
"score": 0,
"time_remaining": 7,
"current_position": 1,
"furthest_progress": 0.1429,
"quiz_positions": [
2,
3,
4,
5,
6,
7
],
"direct_enrollment": true,
"max_quiz_attempts": null,
"attempts_count": 1,
"inactive": null,
"program": null,
"programs": [],
"in_completed_program": false,
"external_id": null,
"estimated_time": 7,
"passing_threshold": 80,
"has_certificate": false,
"course_type": "bridge",
"slide_count": 7,
"attachments_count": 0,
"attachments_count_author": 1,
"third_party_course_id": null,
"open_book": false,
"continuing_education_credits": null,
"features": [
"has_quizzes"
]
},
"tags": []
},
{
"id": "6301",
"enrollable_id": "1",
"enrollable_type": "ProgramEnrollment",
"learnable_id": "1",
"learnable_type": "Program",
"title": "IamaProgram",
"description": null,
"state": "active",
"completed_at": null,
"created_at": "2018-08-27T13:01:07.383-06:00",
"archived_at": null,
"permanently_failed": false,
"data": {
"required": true,
"current_course": {
"id": 19,
"title": "abcde",
"state": "created",
"end_at": "2018-09-03T23:59:59.999-06:00",
"expires_at": null,
"renew_by": null,
"required": true,
"score": 0,
"estimated_time": 2,
"time_remaining": 2,
"passing_threshold": 80,
"has_certificate": null,
"course_type": "bridge",
"slide_count": 2,
"attachments_count": 0,
"current_position": 0,
"furthest_progress": 0,
"learnable_type": "CourseTemplate"
},
"end_at": null,
"expires_at": null,
"furthest_progress": 0,
"inactive": null,
"item_count": 2,
"item_counts": [
{
"item_type": "CourseTemplate",
"count": 2
}
],
"program_index": 1,
"has_certificate": false,
"pending_approval_item_count": 0,
"pending_approval_items": [],
"features": [
"has_quizzes"
]
},
"tags": []
},
{
"id": "6300",
"enrollable_id": "1",
"enrollable_type": "TaskEnrollment",
"learnable_id": "1",
"learnable_type": "Task",
"title": "IamaCheckpoint",
"description": "",
"state": "created",
"completed_at": null,
"created_at": "2018-08-27T12:59:42.541-06:00",
"archived_at": null,
"permanently_failed": false,
"data": {
"requires_approval": false,
"requires_evidence": false,
"direct_enrollment": true,
"required": true,
"program": null,
"programs": [],
"in_completed_program": false,
"end_at": "2018-09-03T23:59:59.999-06:00",
"inactive": null,
"attachments_count": 0,
"attachments_count_author": 0,
"has_certificate": false
},
"tags": []
},
{
"id": "3450",
"enrollable_id": "3450",
"enrollable_type": "Enrollment",
"learnable_id": "4",
"learnable_type": "CourseTemplate",
"title": "Science 101",
"description": null,
"state": "complete",
"completed_at": "2018-08-27T12:37:13.365-06:00",
"created_at": "2017-04-10T16:26:36.368-06:00",
"archived_at": null,
"permanently_failed": false,
"data": {
"end_at": "2017-04-17T23:59:59.000-06:00",
"expires_at": null,
"renew_by": null,
"required": true,
"score": 100,
"time_remaining": 0,
"current_position": 0,
"furthest_progress": 1,
"quiz_positions": [],
"direct_enrollment": true,
"max_quiz_attempts": null,
"attempts_count": 1,
"inactive": null,
"program": null,
"programs": [],
"in_completed_program": false,
"external_id": null,
"estimated_time": 4,
"passing_threshold": 80,
"has_certificate": false,
"course_type": "bridge",
"slide_count": 4,
"attachments_count": 0,
"attachments_count_author": 0,
"third_party_course_id": null,
"open_book": null,
"continuing_education_credits": null,
"features": []
},
"tags": []
}
],
"meta": {}
}`
I just want to get all the courses (learnable_id) which are
State = Created
learnable_type = CourseTemplate
Once I get all the learnable_id which met above condition then I can return random number from that array.
How do I get this?
Thanks in advance.
You can use JSON path to extract json key values by applying required filters
Add a JSON extractor as a child of your request where you are getting above respone.
use the following configuration in JSON extractor
Json path Expression : $..[?(#.learnable_type=='CourseTemplate' && #.state == 'created')].learnable_id
match no : 0 (This will return a random matach from the possible matches in JMeter
as shown below
Debug Sampler Result :
More info :
Extracting variables
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.apache.commons.lang.StringUtils;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
//Get Store total count
int totalLearningItems = StringUtils.countMatches(new String(data), "enrollable_id");
log.info("Total Number of Learning Items are: " + totalLearningItems);
Random rand = new Random();
if (totalLearningItems > 0) {
//Check for Fulfilment type is "Pickup"
String jsonString = new String(data);
JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
JSONObject learning_items = (JSONObject) parser.parse(data);
JSONArray learningArray = (JSONArray) learning_items.get("learning_items");
String learningItemId;
courseList = new ArrayList();
programList = new ArrayList();
taskList = new ArrayList();
for (int i=0; i<learningArray.size(); i++) {
if(learningArray.get(i).getAsString("state").equals("created") || learningArray.get(i).getAsString("state").equals("active")) {
if(learningArray.get(i).getAsString("learnable_type").equals("CourseTemplate")){
courseList.add(learningArray.get(i).getAsString("learnable_id"));
} else if (learningArray.get(i).getAsString("learnable_type").equals("Program")) {
programList.add(learningArray.get(i).getAsString("learnable_id"));
} else if (learningArray.get(i).getAsString("learnable_type").equals("Task")) {
taskList.add(learningArray.get(i).getAsString("learnable_id"));
}
}
}
if(courseList.size() > 0) {
vars.put("courseID", courseList.get(new Random().nextInt(courseList.size())));
} else if (programList.size() > 0) {
vars.put("programID", programList.get(new Random().nextInt(programList.size())));
} else if(taskList.size() > 0) {
vars.put("taskID", taskList.get(new Random().nextInt(taskList.size())));
}
}
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.
Below details is my shipment details. I want to loop through this JSON and get each checkpoint details.
How can I do this with Ruby
This is my controller:
#asd = AfterShip::V4::Tracking.get('ups', '1Z31Y1Y90490064644')
this is my view page where i get json data
= #asd.to_json`
This is the JSON:
{
"meta": {
"code": 200
},
"data": {
"tracking": {
"id": "560b87b38c9079f272e98dfc",
"created_at": "2015-09-30T06:56:51+00:00",
"updated_at": "2015-09-30T06:56:55+00:00",
"last_updated_at": "2015-09-30T06:56:55+00:00",
"tracking_number": "1Z31Y1Y90490064644",
"slug": "ups",
"active": false,
"android": [
],
"custom_fields": null,
"customer_name": null,
"delivery_time": 7,
"destination_country_iso3": "GBR",
"emails": [
"pu#l.com"
],
"expected_delivery": null,
"ios": [
],
"note": null,
"order_id": null,
"order_id_path": null,
"origin_country_iso3": "HKG",
"shipment_package_count": 1,
"shipment_pickup_date": "2015-08-24T16:00:00",
"shipment_delivery_date": "2015-09-01T14:22:00",
"shipment_type": "UPS SAVER",
"shipment_weight": 0.5,
"shipment_weight_unit": "kg",
"signed_by": "MANTON (RESIDENTIAL)",
"smses": [
],
"source": "api",
"tag": "Delivered",
"title": "1Z31Y1Y90490064644",
"tracked_count": 1,
"unique_token": "bkGcaTOJDe",
"checkpoints": [
{
"slug": "ups",
"city": null,
"created_at": "2015-09-30T06:56:55+00:00",
"location": "HK",
"country_name": "HK",
"message": "BILLING INFORMATION RECEIVED",
"country_iso3": "HKG",
"tag": "InfoReceived",
"checkpoint_time": "2015-08-25T23:05:47",
"coordinates": [
],
"state": null,
"zip": null
},
{
"slug": "ups",
"city": null,
"created_at": "2015-09-30T06:56:55+00:00",
"location": null,
"country_name": null,
"message": "YOUR PACKAGE WAS RELEASED BY THE CLEARING AGENCY.",
"country_iso3": null,
"tag": "InTransit",
"checkpoint_time": "2015-08-27T16:57:00",
"coordinates": [
],
"state": null,
"zip": null
},
{
"slug": "ups",
"city": null,
"created_at": "2015-09-30T06:56:55+00:00",
"location": null,
"country_name": null,
"message": "YOUR PACKAGE WAS RELEASED BY THE CLEARING AGENCY.",
"country_iso3": null,
"tag": "InTransit",
"checkpoint_time": "2015-08-27T17:07:00",
"coordinates": [
],
"state": null,
"zip": null
}
}
}
}
What you are getting here is an instance of Hash class (the response JSON is already parsed).
tracking = AfterShip::V4::Tracking.get('ups', '1Z31Y1Y90490064644')
tracking['data']['tracking']['id']
# => "560b87b38c9079f272e98dfc"