How to get the specific json object from laravel blade? - php

I am trying to get specific object from the array which is call previous_position_1_name,right now in my blade
{{$jobseeker - > jobseeker['Myprevious_position_1']}}
it output the json array like:
{
"id": 3,
"previous_position_1_name": "QC",
"created_at": null,
"updated_at": null
}
I just only want to get the previous_position_1_name column which is QC.
Please guide me.

You can use json_decode and then fetch the certain object u want in this case it's previous_position_1_name.
//Decode the json so you can access the objects.. (array)
$json = json_decode($jobseeker,true);
//Access the object you want
$previous_position_1_name = $json['previous_position_1_name'];

Related

Get whole object data instead id in Laravel

I have an object with this structure, that I need to get name of source_id in my blade file,
When I try to access that by the way
$data['source_id']['name']
$data->source_id->name
$data->{'source_id'}->{'name'}
I got this error
Trying to get property 'name' of non-object
I just try this $data->source_id, but it return its ID, instead the object,
any suggestion?
{
"id": 4,
"type": "s1",
"source_id": {
"id": 1,
"code": "۱",
"name": "تیل پطرول",
"manager": "نجیب",
"phone": "۰۷۷۲۴۳۴۳۲۱",
"address": "دهمزنگ",
"capacity": "0.00",
"oum_id": 1,
"created_at": "2021-03-02T15:55:20.000000Z",
"updated_at": "2021-03-02T15:55:20.000000Z"
},
"source_type": "STRG",
}
Here is the function to get data
public function loadSale($id){
$base = Sale::findOrFail($id);
if ($base->type == "s1") {
$sale = Sale::with(['saleS1.project.pro_data', 'source_id'])->where('id', $id)->first();
$sale['sales'] = $sale->saleS1;
}
return $sale
}
I could understand your problem. But it is an object not an array. You have to use a loop to access the object. Create a for loop and and inside which you can access the particular field of the object. Hope this helpful
As #MAY mentioned in the comment
I guess the name of your relation and foreign key field is same, that's why you get id when you do this $data->source_id
So I modify the relation and define the source, now I can't access the data simply as before $data->source->name

Merge two json array into one

Tried merging two JSON responses into a single one but the problem is the data is displayed in two arrays and I want it in a single array. How do I achieve it in Lumen/Laravel
Tried contatinating two arrays or responses
public function index(Request $request)
{
$post = Post::orderBy('id', 'DESC')->get();
$post_images = PostImage::orderBy('id', 'DESC')->get();
return $this->successResponse($posts.$post_image );
}
Expected:-
{
"post": {
"id": 14,
"post_id": 798965728,
"user_id": 1,
"location": "first",
"title": "un8852",
"cooked_time": "1554329910",
"dispose_time": "1554373110",
"food_type": "nv",
"description": "asdfg",
"serve_quantity": 23,
"lat": 19.08,
"lon": 73,
"id": 10,
"post_id": 798965728,
"image_name1": null,
"image_name2": null,
"image_name3": null,
"image_name4": null,
"image_name5": null,
},
"st": "1",
"msg": "success"
}
Got:-
{
"post":"{\"id\":14,\"post_id\":798965728,\"user_id\":1,\"location\":\"first\",\"title\":\"un8852\",\"cooked_time\":\"1554329910\",\"dispose_time\":\"1554373110\",\"food_type\":\"nv\",\"description\":\"asdfg\",\"serve_quantity\":23,\"lat\":19.08,\"lon\":73,\"created_at\":\"2019-04-04 10:20:18\",\"updated_at\":\"2019-04-04 10:20:18\"}{\"id\":10,\"post_id\":798965728,\"image_name1\":null,\"image_name2\":null,\"image_name3\":null,\"image_name4\":null,\"image_name5\":null,\"created_at\":\"2019-04-04 10:20:18\",\"updated_at\":\"2019-04-04 10:20:18\"}",
"st":"1",
"msg":"success"
}
There are some missing pieces there, but I think I see what's happening.
Based on the result you're getting, it looks like $posts and $post_image in this code are eloquent models.
return $this->successResponse($posts.$post_image );
When you concatenate them, their __toString() methods convert them to strings, which is done using the toJson() method. So basically you have two JSON objects stuck together, which isn't valid JSON, and then the successResponse() method encodes them again.
To merge them, you can convert them to arrays, merge those, then pass the result to successResponse().
$merged = array_merge($posts->toArray(), $post_image->toArray());
return $this->successResponse($merged);
The result you want is impossible, though. The "post" object has two different values of "id". You'll only be able to get one. If you use
$merged = array_merge($posts->toArray(), $post_image->toArray());
Then the id value of the second object will replace the first one. If you want to keep the first id value, you need to use union instead of array_merge.
$merged = $a->toArray() + $b->toArray();
You can definitely concatenate two JSON arrays, You have to parse the objects and concatenate them and re stringify.
This question might be answered here also. https://stackoverflow.com/a/10384890/1684254
I think you can't concatenate 2 JSON objects as strings.
The proper way would be to:
Get the Post and the PostImage objects
$post = Post::orderBy('id', 'DESC')->get();
$post_images = PostImage::orderBy('id', 'DESC')->get();
Serialize the Post object
https://laravel.com/docs/5.8/eloquent-serialization
Use the method described below to add each field of the PostImage object (image_name1 .. image_name5) to the JSON
How to add attribute in JSON in PHP?
Return the JSON
Update:
Post::orderBy('id','DESC')->get()-> first() returns one object.
Post::orderBy('id','DESC')->get() returns a collection of objects and it would require a different approach.
Try this:
$post = Post::orderBy('id', 'DESC')->get();
$post->map(function ($item, $key) {
$post_images = PostImage::where('post_id', $item->id)->get()->first();
$item->setAttribute('image_name1',$post_images->image_name1);
$item->setAttribute('image_name2',$post_images->image_name2);
$item->setAttribute('image_name3',$post_images->image_name3);
$item->setAttribute('image_name4',$post_images->image_name4);
$item->setAttribute('image_name5',$post_images->image_name5);
return $item;
});
return $this->successResponse($posts);

Search an array nested in a laravel collection

I have a api call that returns a set of data something like this:
{
"id": 97423,
"visitor_id": 231505,
"domain_sessionidx": 1,
"session_start": "2017-06-01 04:40:07",
"session_end": "2017-06-01 05:22:45",
"session_length": 2558,
"count_pages": 11,
"count_pings": 7,
"created_at": null,
"updated_at": "2017-06-12 18:59:51",
"pages": [
1829,
1811,
1829,
1501,
1829,
1889,
1762,
1686,
1825,
1825,
1825
] },....
I have put this into a variable and made a collection out of it:
$new_var = collect($result);
I am having a problem because I would like to access only the records in the data where pages contains the id 1762. I have been trying with:
$new_var->whereIn('pages',[1762])->pluck('pages')
but I am always getting an empty result. Any help is greatly appreciated.
I feel like you need to filter your $new_var collection and return true if it's pages attribute contains the page you are looking for. For example:
$page = 1762;
$inPages = $new_var->filter(function($collection) use($page){
return in_array($page, $collection->pages);
});
$inPages should now be a subset of $new_var with entries that contain 1762 in their pages array, otherwise it will be an empty Collection. Check here for more information: https://laravel.com/docs/5.4/collections

Can't access object variables in PHP from Facebook Graph API

I have a request to the Facebook Graph API that returns a post from a facebook account.
I am simply trying to access the data instance of the object returned in PHP but everything I have tried returns NULL.
Sample response
{
"data": [
{
"id": " 111111111111111111100000",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}
I want to get at the array of objects data provides so I can MVC the data returned in a larger response.
This doesn't currently work:
$response->data; // returns null
$response[0]->data; // returns null
$response->data[0]; // returns null
Feel I'm missing something obvious.
first decode it with json_decode then trying to access the data object
$res = json_decode($response);
print_r($res->data);
print_r($res->data[0]->id);
print_r($res->data[0]->message);
code
you have to use first json decode function so you can get the data from the json response.
$response = '{
"data": [
{
"id": "143384725674462_1592535354092718",
"message": "Coming soon #PERFECTFIT 05.07.17 👀\nRegister to be one of the first to find out what it is here ⬇️\nhttp://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"created_time": "2017-06-26T17:39:20+0000",
"link": "http://www.bathrugby.com/the-club/supporters/perfect-fit-register/",
"full_picture": "https://scontent.xx.fbcdn.net/v/t39.2147-6/19284954_1592534984092755_4946207882807869440_n.jpg?oh=56cc96435f423cec31962966b6f689c2&oe=59DB08B6"
}
]
}';
$response = json_decode($response);
print_r($response->data[0]->id);
print_r($response->data[0]->message);

How to save data through objects which are in array in Laravel

I m newbee in laravel. I am sending such type of response through Postman. and in Laravel controller I m getting this response in $request.
[{
"id": 40,
"cname": "Ramesh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "111",
"input2": "111"
}, {
"id": 45,
"cname": "Suresh",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "222",
"input2": "222"
}, {
"id": 49,
"cname": "Raj",
"constraint_value": "",
"r_id": "6",
"rtype_id": null,
"deleted_at": null,
"created_at": null,
"updated_at": null,
"input": "333",
"input2": "333"
}]
I am facing difficulty in
How to count the total no of objects in array which I am receiving in $request. I had used count($request) or sizeOf($request) but its returning only 1 although there are 3 arrays. Help me in this.
How to save the data in database through such arrays.I want to save the values of input and input2.
Probably late, but may help someone in the future. First of all. You need to iterate over the array of objects like so
foreach($request->all() as $key => $value){
$model = new Model();
$model->attribute1 = $value['attribute1'];
$model->attribute2 = $value['attribute1'];
$model->attributeN = $value['attributeN']; // where N is infinite # of attr
$model->save();
}
So what is happening is that each time the loop iterates, it create a new object of your Model type inside the loop and assigns the objects attributes from the array key values and persists in DB and repeats until all the objects in the array are finished. The
$model = new Model();
is necessary so that each time loop iterates It creates a new object and persists. The loop may save only one object if u do not create it each time the N iteration occurs. This may happen if u are creating the model object in the constructor where it is instantiated once when the constructor is run.
Hope this helps.
Try to convert it to an array:
$data = json_decode($request, true);
$count = count($data); // Count number of elements.
Model::insert($data); // Insert all elements into DB.
Don't forget to validate any input first and add all fields except timestamps to a $fillable array.
You can try this..
$data = [{},{}]; // your response
$count = 0;
foreach($data as $obj)
{
Model::create($obj); //save the model
$count ++;
}
echo $count // your count
its quit simple
$request ='[ {"id":40,"cname":"Ramesh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"111","input2":"111"}, {"id":45,"cname":"Suresh","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"222","input2":"222"}, {"id":49,"cname":"Raj","constraint_value":"","r_id":"6","rtype_id":null,"deleted_at":null,"created_at":null,"updated_at":null,"input":"333","input2":"333"}]';
$request = (array)json_decode($request, true);
now use them as you usually use .
I got the solution. I was making mistake in sending the data from angularjs.I was directly sending the POST request without creating its object like var data = { 'data':my_request} .That is why request was reeving with instance in laravel. But, as I start sending data by creating its object its working. This was the solution for my first problem. Help me how to store that received data in database.

Categories