I am using Laravel 5.7 to build an API that provides a JSON response. I am creating the following JSON but it needs some changes. Table contain booking_pics columns in which multiple images stored using , separated. I want fetch in json as object in array. i am display json but only last image is display others is not, need solution.
Controller:
$get_booking_details= DB::table('table_booking_list')
->join('table_booking_details', 'table_booking_list.booking_id', '=', 'table_booking_details.booking_id')
->select('table_booking_details.*')
->where('table_booking_details.booking_id',$booking_id)
->get();
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics=[["image" => $items]];
}
}
return response()->json(['success' => '1','data' =>$get_booking_details]);
json response:
{
"success": "1",
"data": [
{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}
]
}
Required json:
{
"success": "1",
"data": [{
"id": 1,
"booking_list_id": 1,
"booking_id": 1,
"booking_name": "hockey stadium",
"booking_area": "kolhapur",
"booking_status": 0,
"time": "6.00 am to 8.00pm",
"booking_pics": [{
"image": "http://192.168.1.132:8000/images/ground_pic/1.jpg"
},
{
"image": "http://192.168.1.132:8000/images/ground_pic/2.jpg"
}
],
"available_sports": "hockey,cricket",
"booking_amenities": "parking,toilet,water",
"booking_rating": 4.5,
"booking_area_address": "MSEB Ring Road, Datta Colony, Kolhapur, Maharashtra, 416008",
"longitude": "85.501980",
"latitude": "23.624420",
"updated_at": "2019-06-26 16:42:02",
"created_at": "0000-00-00 00:00:00"
}]
}
Do it this way
foreach($get_booking_details as $item)
{
foreach(explode(",",$item->booking_pics) as $items)
{
$item->booking_pics["image"][] = $items;
}
}
fastest way would be creating a model and casting the data from database as a json
in model
protected $casts = [
'booking_pics' => 'json',
];
Related
$filtered_restros= new \Illuminate\Pagination\CursorPaginator($restaurants, 1);
$data['message'] = "Restaurants fetched successfully";
$data['status'] = "success";
$data['data'] = $filtered_restros;
I did this code and i'm getting fallowing results
{
"message": "Restaurants fetched successfully",
"status": "success",
"data": {
"data": [
{
"id": 5,
"name": "HB Town Restro",
"email": "2321efsd#gmail.com",
"phone_number": "12",
"mobile_number": "454554354",
"address": "hjgjghioiu",
"pincode": "4400255241653",
"latitude": "21.150964",
"longitude": "79.150516",
"restro_type": 1,
"cuisine_type": "American",
"book_now_btn": 1,
"queue_btn": 0,
"is_saved": 0,
"restro_cuisines": [
{
"cuisine_id": 5,
"cuisine_name": "North indian"
}
],
"seating_options": [
"Cafeteria",
"fghfghf",
"Cafeterias",
"indoor"
],
"description": "gj",
"menu_category": "5",
"parking": "Onsite",
"image": "http://localhost/projectx/public/restaurants/hb.jpg",
"status": 1
}
],
"path": "/",
"per_page": 1,
"next_page_url": "/?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9",
"prev_page_url": null
}
}
after hitting the "next_page_url"
http://localhost/projectx/api/user/explore_all_restaurants?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9
this printing same results as above means cursor pagination is not working.
When i did same thing using eloquent
$users = DB::table('restros')->orderBy('id')->cursorPaginate(15);
its working properly and pagination is also working and full next page url are automatically generating. but its using eloquent and i want to do the cursor pagination on my processed array and its not working properly.
In short i'm asking how to do cursor pagination on custom array.
I am creating a json file from my array:
$file = json_encode($array);
The json file will look like this:
[
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
But I need to create a json file with some little bit different format. The output I need is:
{
"draw": 1,
"recordsTotal": 5000,
"recordsFiltered": 5000,
"data": [
{
"name": "file1.html",
"date": "2019-01-29T20:33:57.000163Z",
"size": "348"
}
{
"name": "file2.xml",
"date": "2019-01-29T20:33:57.000167Z",
"size": "401"
}
{
"name": "file3.html",
"date": "2019-01-29T20:33:57.000171Z",
"size": "1314"
}
]
}
Is this possible with json_encode?
Create a new array with rest of the info and assign current array data into it as well.
$newArray = array(
'draw'=> 1,
'recordsTotal'=> 5000,
'recordsFiltered'=> 5000,
'data'=>$array
);
$file = json_encode($newArray);
I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.
I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);
A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.
I have this data in method of controller as you see I deleted some keys in method:
$foods = Food::get()->map(function($value){
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
return HttpHelpers::sendJsonData($foods, 200);
and the api response returns this:
{
"success": true,
"data": [
{
"id": 1,
"title": "food1",
"default_price": 2353465456,
"main_meal": 1,
"labels": [
{
"id": 1,
"title": "type1",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 1,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
},
{
"id": 2,
"title": "food2",
"default_price": 1000,
"main_meal": 0,
"labels": [
{
"id": 1,
"title": "type2",
"type": "food",
"created_at": "2018-08-23 03:55:33",
"updated_at": "2018-08-23 03:55:33",
"pivot": {
"labelable_id": 2,
"label_id": 1,
"labelable_type": "App\\Models\\Panel\\Food"
}
}
]
}
]
}
now my problem is that I do not want to return some keys, like labalable_id and labelable_type in pivot and created_at in labels, please offer me the best way
You can use the makeHidden method for hiding data to JSON. Haven't tried this code but, i think it should work.
https://laravel.com/docs/5.6/eloquent-serialization#hiding-attributes-from-json
$foods = Food::get()->map(function($value){
foreach($value->labels as $label){
$label = $label->makeHidden(['created_at']);
$label->pivot = $label->pivot->makeHidden(['labelable_id', 'labelable_type']);
}
return collect($value->toArray())->except('pivot', 'deleted_at', 'created_at', 'updated_at');
});
If the data response is coming through the stored procedure then in that case you need to store the Pivot table data in a temporary table and select the required keys that you require and display it through API in json.
I get data from database using this query
$cats = Category::with(['cat_trans' => function($q) use($lang){
$q->where('lang_code', $lang);
}])->with(['cat_prod' => function($query) use ($lang,$currency){
$query->with(['pro_trans' => function ($q) use ($lang){
$q->where('lang_code', $lang);
}]);
////////////
$query->with(['pro_price' => function ($q) use ($currency){
$q->with('currency_code')->where('cur_code', $currency);
}]);
///////////
}])->whereHas('account_type', function($qr) use ($account_type){
$qr->where('account_type_id', $account_type);
})->get();
I'm trying to remove the empty objects from the result, when I tried this I got the following response
{
"1": {
"id": 1,
"parent_id": null,
"order": 1,
"name": "Moblie",
"slug": "mobile-1",
"created_at": "2018-07-08 09:41:08",
"updated_at": "2018-07-08 10:30:17",
"cat_trans": [
{
"id": 1,
"category_id": 1,
"field": "title",
"value": "Mobile",
"lang_code": "en",
"created_at": "2018-07-08 09:51:59",
"updated_at": "2018-07-08 09:51:59"
},
{
"id": 2,
"category_id": 1,
"field": "desc",
"value": "smart",
"lang_code": "en",
"created_at": "2018-07-08 09:52:41",
"updated_at": "2018-07-08 09:52:41"
},
{
"id": 12,
"category_id": 1,
"field": "slug",
"value": "mobile-1",
"lang_code": "en",
"created_at": null,
"updated_at": null
}
],
}
}
I want to remove the key "1" from all the responses.
I used unset to get this value using this code
foreach ($cats as $k) {
if (count($k->cat_prod) == 0) {
unset($cats[$va]);
}
$va++;
}
Then I tried using array_values but it displays that I can just use array_values on an array not an object.
You can remove key "1" by simply doing
array_values((array)$cats)
You were receiving error for this function like "Can Only be used on array" was due to Laravel Query returns object , so you just need to do type conversion on it.
$cats->toArray() if u need either to convert object to array or convert with some specific conditions
Your output looks like JSON so you can do this to eliminate the 1:
json_encode( $cats->{1} );
You can use laravel simple method mapWithKeys()
$cats = $cats->mapWithKeys(function ($item) {
return $item > 2;
});
$keyed->all();