need to implement array push in forloop - laravel-5

----------------------Code --------------------------
public function event_requests(){
$Uid = Input::get('Uid');
$token = Input::get('token_code');
$time = Input::get('time');
if(App_user::where('ID', '=', $Uid)->where('token_code', '=', $token)->count() > 0){
$result = DB::table('Ball_invites')
->join('Ball_users','Ball_users.ID', '=', 'Ball_invites.people')
->select('Ball_users.*', 'Ball_invites.Eid')
->Where('Ball_users.Pid', '=', $Uid)
->orWhere('Ball_users.ID', '=', $Uid)
->get();
foreach ($result as $val){
$eis[] = $val->Eid;
$eids = array_unique($eis);
}
$event = DB::table('Ball_event')->whereIn('ID', $eids)->get();
$resultdataa = array();
foreach($result as $new){
$resultdataa[$new->Eid] = $new;
}
$resultdata = json_decode(json_encode($resultdataa), true);
$data = array();
foreach($event as $key){
$data[$key->ID] = $key;
}
$dataa = json_decode(json_encode($data), true);
$final = array();
foreach($dataa as $key2=>$val2){
foreach($resultdata as $key1=>$val1){
if($key2 == $key1){
$arrs[] = $val2;
$arrss[] = $val1;
print_r($val1);
}
}
}
return Response::json(array('status'=>200,'result'=>$final));
} else {
return Response::json(array('status'=>'401','msg'=>'session expired'));
}
}
--------------------- Need Record like this ----------------------
Editor Note: the data structure below looks like it is desired to be JSON,
but I'm not sure what to make of the nested array in a bad location.
{
"status": 200,
"result": [
{
"ID": 63,
"Uid": 86,
"event_type": 1,
"event_title": "Testing",
"event_location": "Home",
[
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
},
{
"ID": 141,
"Pid": 139,
"fname": "Veronica",
"lname": "khiwani",
"nick_name": "Ronnie",
}
]
},
{
"ID": 64,
"Uid": 139,
"event_type": 2,
"event_title": "cricket match",
"event_location": "london",
}
]
}

Related

Format array output to be readable by chartjs in Laravel

This is my query to get the product name and total quantity sold.
$prd = DB::table('order_details')
->join('products', 'order_details.product_id', '=', 'products.id')
->select('products.name', DB::raw('SUM(quantity) as quantity'))
->groupBy('products.name')
->orderBy('quantity', 'desc')
->get();
return $prd;
This is the output.
[
{
"name": "PINK",
"quantity": "22"
},
{
"name": "WHITE",
"quantity": "14"
},
{
"name": "RED",
"quantity": "13"
}
]
But I need it to be in this format. For it to work with chartjs.
{
"PINK": 22,
"WHITE": 14,
"RED": 13
}
This is what I've so far. I tried to use collection map. But I'm not sure how to return the quantity portion. Any pointers?
return $prd->groupBy('name')->map(function ($item, $key) {
return ''; // what should I return here to get the qty?
});
Current half baked output
{
"PINK": "",
"WHITE": "",
"RED": "",
}
You can use pluck() instead of get() for this:
$prd = DB::table('order_details')
->join('products', 'order_details.product_id', '=', 'products.id')
->select('products.name', DB::raw('SUM(quantity) as quantity'))
->groupBy('products.name')
->orderBy('quantity', 'desc')
->pluck('name', 'quantity');

Laravel- How to Remove a key from collection?

I have data as below:
[
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
"price": 20
}
]
I want to filter which is is_lottery == false remove the price key from this collection. The output is:
[
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
}
]
You can do this
$json = '[
{
"id": "3",
"title": "Boruto\'s Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "3",
"title": "Misuki\'s Photo",
"is_lottery": 0,
"price": 20
}
]';
$filtered = collect(json_decode($json, true))->map(function ($array) {
if (!$array['is_lottery']) {
unset($array['price']);
}
return $array;
});
For native PHP you can do
$data = json_decode($json, true);
foreach ($data as $index => $array) {
if (!$array['is_lottery']) {
unset($array['price']);
}
$data[$index] = $array;
}
$json = [
{
"id": "3",
"title": "Boruto's Photo",
"is_lottery": 1,
"price": 10
},
{
"id": "4",
"title": "Misuki's Photo",
"is_lottery": 0,
"price": 20
}
];
$filtered = collect(json_decode($json))->map(function($value, $key) {
if (!$value['is_lottery']) {
Arr::except($value, 'price');
}
return $value;
});
you can declare new variable called $newCollection as final collection. Use foreach() to iterate your collection then delete the is_lottery from collection by using unset() then push it to $newCollection, this is example how you can delete it using foreach:
$newCollection = [];
foreach ($photos as $key => $value) {
if ($value["is_lottery"] == 0) {
unset($value["price"]);
}
array_push($newCollection,$value);
}
or you can try using forget to remove it from collection (not tested) from this ref:
How to unset (remove) a collection element after fetching it?

Get value of nested array from json

I have some JSON data which get from an API. I need only the products name from there. How can I get this? I am already trying with foreach loop but I can't. I am using laravel framework version 6.0
[
{
"id": 2,
"name": "Bijj",
"categories": [
{
"id": 10,
"name": "Rice",
"sbu": 2,
"products" : [
{
"id": 25,
"name": "Rajkumar",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
},
{
"id": 50,
"name": "Sera",
"skus": [],
"short_description": "বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান",
}
]
},
{
"id": 20,
"name": "Vhutta",
"sbu": 2,
"products" : [
{
"id": 129,
"name": "Pack-139",
"skus": [],
"short_description": "মোচায় ৮৬ % দানা ও ১৪ % শাঁস",
},
{
"id": 125,
"name": "Don-12",
"skus": [],
"short_description": "সারা বৎসর চাষ উপযোগী",
}
]
}
]
}
]
I want to get only the all products name form there.
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
After decode you can simply use this helper
use Illuminate\Support\Arr;
Arr::only($array, ['categories.products.name']);
or
Arr::only($array, ['categories.*.name']);
you want get only product's name ??
and if your data array then you have to change $value['id']
$product_names = [];
foreach ($getSbu as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
foreach ($category->products as $product) {
$product_names[] = $product->name;
}
}
}
}
dd($product_names);
foreach (json_decode($getSbu) as $value) {
Foreach works in an array so first you must decode it in order to parse it as an array.
Since you use object parsing you don't have to use parameter true in your json_decode function. If you want an array instead of an object you can use:
foreach (json_decode($getSbu,true) as $value) {
but then you access your value like array fields, for example value['id']
Your code should look like:
$getSbu = Helper::CreateGuzzleHttpClient('sbu');
foreach (json_decode($getSbu) as $value) {
if($value->id == 2) {
foreach ($value->categories as $category) {
$products = $category->products;
}
}
}
Leverage aravel collections
// this is just ur data but as json string
$var = '[{"id":2,"name":"Bijj","categories":[{"id":10,"name":"Rice","sbu":2,"products":[{"id":25,"name":"Rajkumar","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"},{"id":50,"name":"Sera","skus":[],"short_description":"বাংলাদেশের আবহাওয়া উপযোগী হাইব্রিড ধান"}]},{"id":20,"name":"Vhutta","sbu":2,"products":[{"id":129,"name":"Pack-139","skus":[],"short_description":"মোচায় ৮৬ % দানা ও ১৪ % শাঁস"},{"id":125,"name":"Don-12","skus":[],"short_description":"সারা বৎসর চাষ উপযোগী"}]}]}]';
$objCollection = collect(json_decode($var, true));
$productNames = $objCollection->pluck('categories.*.products.*.name');
dd($productNames);

Paginate while returning array Api resource object

I need to send multiple object to the api resources. So I am returning multiple Object inside array.Everything works fine but not showing any pagination meta data. like Current_page,next_page url etc.
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
My resource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class ServiceProviderCollection extends Resource
{
public function toArray($request)
{
return
[
'name'=>$this->forename,
'rating'=>$this->rating,
'price'=>$this->price,
'distance'=>round($this->distances,1),
];
}
}
My Controller:
here I have two type of users . near_by users and Users across the city. I sent them to the ServiceProviderCollection As an array.
$user_city = $userObj->location->city;
$locationObj = Location::whereNotIn('id', $blockeduser)->where('city',$user_city)->first();
$across_city = $locationObj->users()->simplePaginate(20);
$near_by = User::join('locations as l', 'users.location_id', '=', 'l.id')
->select('users.*', DB::raw('(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) * cos(radians(`lat`)) * cos(radians(`lng`) - radians(' . $coordinates['longitude'] . ')) + sin(radians(' . $coordinates['latitude'] . ')) * sin(radians(`lat`)))) as distances'))
->having('distances', '<', $max_distance)
->orderBy('distances', 'ASC')
->where('role_id',2)
->whereNotIn('id', $blockeduser)
->simplePaginate(20);
return [
'across_city' => ServiceProviderCollection::collection($across_city),
'near_by' => ServiceProviderCollection::collection($near_by)
];
I want Json Data with pagination.
{"data":{
"across_city": [
{
"name": "??",
"rating": 0,
"price": 0,
"distance": 0,
}
],
"links": {
"first": "",
"last": "",
"prev": null,
"next": ""
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "",
"per_page": 2,
"to": 2,
"total": 6
},
{
"near_by": [
{
"name": "??",
"rating": 0,
"price": 0,
"distance": 0,
}
],
"links": {
"first": "",
"last": "",
"prev": null,
"next": ""
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "",
"per_page": 2,
"to": 2,
"total": 6
}
}
I have no idea, what the purpose of ServiceProviderCollection is. If it creates a regular collection then there is a better way to do so.
To be able to paginate a simple collection you need to add this helper function to your base:
function paginateCollection($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
return new \Illuminate\Pagination\LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
With this function in place you can make
return [
'across_city' => paginateCollection(collect($across_city), 20),
'near_by' => paginateCollection(collect($near_by), 20)
];
Edit
Do you have generated the corresponding resource collections?
Like so: php artisan make:resource Cities --collection
If so, you can return a paginated resource collection

Laravel : Search Query filter

I have searchDetails array in my search. I have done all other search and get data on filter, Problem is that when i search with stone_min, stone_max I get data if there is only one searchDetails array, if there is two data it is return null. How can i do this ? I want search with stone_min, stone_max for particular product_id.
what i try :
Example for data to search :
{
"limit": 1000,
"offset":0,
"user_id": "",
"min_price": "",
"max_price": "",
"searchDetails": [
{
"product_id": "1",
"attributeId": [],
"is_exclude": "no",
"stone_min": "5",
"stone_max": "15"
},
{
"product_id": "2",
"attributeId": [],
"is_exclude": "no",
"stone_min": "100",
"stone_max": "500"
}
]
}
My query for getting all data
$searchablePost = Post::with(['product','postattribute.attribute.category','user.userDetails'])
->whereIn('product_id', $userApprovalProductIDs)
->where('status', 'Active')
->whereIn('demand_or_supply', $demand_or_supply);
Search for min-max stone :
if (count($searchDetails) > 0) {
$j = 0;
foreach ($searchDetails as $value) {
if (strtolower(trim($value['is_exclude'])) == "no") {
$searchablePost = $searchablePost->where(function ($query) use ($value) {
if ($value['stone_min'] && $value['stone_max']) {
if (isset($j) && $j == 0){
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
} else {
$query->where('stone_min', '>=', $value['stone_min'])->where('stone_max', '<=', $value['stone_max'])->where("product_id", (int)$value['product_id']);
}
}
});
}
}
}
$searchedPost = $searchablePost->offset($offset)->limit($limit)->orderBy('id','desc')->get();
If you want to search between stone_min and stone_max for particualar product then do:
$request = json_decode($request->searchDetails, true);
$stoneMinMax = collect($request)->pluck('stone_min', 'stone_max');
Product::where(function($q) use($productId) ($stoneMinMax){
$q->where('product_id', $productId)
->whereBetween('stone_column', $stoneMinMax->toArray());
})->get();

Resources