select data based on the array - laravel

I have an array from query like below:
array:84 [
0 => array:2 [
"comp" => "50007148"
"cus" => "F0401"
]
1 => array:2 [
"comp" => "50007148"
"cus" => "J0050"
]
2 => array:2 [
"comp" => "50007148"
"cus" => "L"
]
3 => array:2 [
"comp" => "50007148"
"cus" => "LT"
]
4 => array:2 [
"comp" => "50007148"
"cus" => "RP"
]
Now I need to write a query where comp, cus in above query.
$rslt = Stdetl::whereIn('comp, cus', $categories)
->where(YEAR(docdate), '=', 2019)
->get(SUM(number))->toArray();
But this query is not working. I am getting error as follows:
(1/1) FatalErrorException
Call to undefined function App\Http\Controllers\YEAR()
But this is not the only mistake in that query .

YEAR() is a mysql function, you should use whereRaw() to query this. Like this:
->whereRaw('YEAR(docdate) = 2019')
Update:
For your whereIn() part, you have to make two queries, one for each column. So you will have to get the correct values from the array. This can be done using array_map.
For example:
->whereIn('comp', array_map(function($cat) { return $cat['comp']; }, $categories))
->whereIn('cus', array_map(function($cat) { return $cat['cus']; }, $categories))

You can't use whereIn like that, use this way
$rslt=Stdetl::whereIn('comp', $categories)
->whereIn('cus', $categories)
->where(date('Y', strtotime(docdate)), '=', 2019)
->get(SUM(number))->toArray();;

Related

Larvel Query Builder group By with pluck

id
agent_id
currency
1
A0001
IDR
2
A0002
MYR
3
A0001
THB
example currently have a dataset as above,
is it have any way to using only 1 query builder to get the outcome like below
Output:
[
"agent_id" => "A0001",
"currency" => [
"IDR",
"THB",
],
],
[
"agent_id" => "A0002"
"currency" => ["MYR"]
]
Basically likes try to pluck the currency under same agent
Appreciate for all the suggestion.
Found a solution for this problem
$output = $output
->get()
->groupby('agent_id')
->map(function($rows){
return [
"agent_id" => $rows[0]['agent_id'],
"currency" => $rows->pluck('currency'),
];
});

How to use groupBy Month and Sum in laravel MongoDB

Query to get monthly orders (total orders per month(count) or total sales per month(sum)):
Tried this query, but it is not working. Also tried with other results from StackOverflow, but I didn't understand how it is done with MongoDB query. This is the link to that question : select-sum-column-and-group-by-with-mongodb-and-laravel
$monthly_orders = Order::select(
DB::raw('sum(total_amount) as sum'),
DB::raw('YEAR(created_at) year, MONTH(created_at) month'),
)
->groupBy('month')
->get();
When I try to get total amount by using group by customer ID , it is returning sum as null
$monthly_orders = Order::selectRaw('sum(total_amount) as sum, customer_id')
->groupBy('customer_id')
->pluck('sum', 'customer_id');
Result :
Illuminate\Support\Collection {#2123 ▼
#items: array:4 [▼
"6098e5ff5977a25ee96a2a42" => null
"60dbf87f7d8ffb7cdb2233d2" => null
"605af409195d8e59e34893f2" => null
"60ddae4a66fb69678e45f056" => null
]
}
Try using raw and aggregate
$monthly_orders = Order::raw(function ($collection) {
return $collection->aggregate([
[
'$group' => [
"_id" => '$customer_id',
'customer_id' => ['$first' => '$customer_id'],
'sum' => ['$sum' => '$total_amount']
]
],
]);
});
you can use pluck
$monthly_orders->pluck('sum','customer_id')
Group by month
$monthly_orders = Order::raw(function ($collection) {
return $collection->aggregate([
[
'$group' => [
"_id" => ['$month'=>'$created_at'],
'customer_id' => ['$first' => '$customer_id'],
'sum' => ['$sum' => '$total_amount']
]
],
]);
});

get a data from an array

get a data from an array ..code for getting cart
public function show()
{
$data = $this->cartService->getCart(auth()->user()->id);
dd($data);
}
Response
array:2 [
"cart" => array:9 [
"id" => 244
"user_id" => 53
"total_mrp" => "56000.00"
"promo" => "HELLO"
"discount" => "30.00"
"meta" => {#1575
+"sub_total": 56000
}
]
"cart_items" => array:1 [
]
]
]
]
HOW CAN I GET PROMO IN A Variabel???
i tried
return $data->promo;
but error
You can use collect(). You can read about this function from laravel doc
$data = $this->cartService->getCart(auth()->user()->id);
$cart = collect($data['cart']??[]);
dd($cart->get('promo'));

How to access data from an array when it's inside an std object? Error: Illegal string offset 'id'

How to access this array object in Laravel 6, using Eloquent?
[line_items] => Array
(
[0] => stdClass Object
(
[id] => 4088662196333
[variant_id] => 29653605285997
$external = DB::table('orders')->pluck('import_order_data');
...
foreach ($external as $key => $val) {
...
Cart::updateOrCreate([
'line_item_id' => ['line_item_id' => $val['id']],
],
ErrorException
Illegal string offset 'id'
If I change it to:
'line_item_id' => ['line_item_id' => $val->id],
I get error:
ErrorException
Trying to get property 'id' of non-object
If I change it to:
'line_item_id' => ['line_item_id' => $val['line_items']->id],
I get error:
Illegal string offset 'line_items'
EDIT:
The problem was:
protected $casts = [
'import_order_data' => 'array',
];
Now I can access it like this:
dd($val['line_items'][0]['id']);
Which provides:
4092309209197
or
dd($val['line_items']);
which provides:
array:1 [▼
0 => array:26 [▼
"id" => 4092309209197
"sku" => "1605"
"name" => "Printer Ink"
Any better options on accessing the data?
EDIT:
Answer:
foreach ($val['line_items'] as $index => $lineItem) {
dd($lineItem['id']);
Which provides:
4092309209197
Is this a reasonable way to do it?
If I understand correctly, your array looks like this:
$arr = [
[
"id" => 4092309209197,
"sku" => "1605",
"name" => "Printer Ink",
....etc.....
]
];
Fine. First, since the outer array only has one item, you can do this:
$innerArr = $arr[0];
Now you've got this:
$innerArr = [
"id" => 4092309209197,
"sku" => "1605",
"name" => "Printer Ink",
....etc.....
]
And you can access it like this:
echo $innerArr["id"];
echo $innerArr["sku"];
....etc....
Or like this:
foreach($innerArr as $key => $val){
echo $key.": ".$val."\r\n";
}

Replicating models across 2 systems

I have 2 systems which are seperate from each other. To let them communicate I have built an API. Both systems have common Models, one of which is a Project Model with all its relationships.
Within System A, to send a Project with its relationships I do the following.
$client = new GuzzleHttp\Client();
$jsonProject = json_encode(Project::with('projectType', 'projectType.projectTypeData',
'projectAssets', 'projectAssets.projectAssetsData')->find($project->id));
$req = $client->request('POST', 'https://someurl/postProject', [
'body' => json_encode($jsonProject),
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonProject),
]
]);
Within System B I have the routes set up, and when the above is posted the following is triggered
public function store(Request $request)
{
$project = $request->all();
dd($project);
}
When I make the post request from System A I see something like this because of the dump in System B (I have removed a lot of the output to cut down on code).
array:17 [
"id" => 3
"projectName" => "Test Project"
"user_id" => 1
"contact" => "John Doe"
"project_type" => array:7 [
"id" => 3
"project_id" => 3
"project_type_data" => array:1 [
0 => array:8 [
"id" => 5
"projectType" => "Standard"
]
]
]
"project_assets" => array:7 [
"id" => 2
"project_id" => 3
"project_assets_data" => array:4 [
0 => array:8 [
"id" => 5
"label" => "Logo"
"altTag" => ""
"urlPath" => ""
"projectAssetsId" => 2
]
]
]
]
So everything seems to work fine. My question is this. System B now has a load of json data containing all the data required to make the models. If I was able to send a model via the api (not json) then I could easily create the model within System B. Because it is json data however, and I cant decode it because it is not a string, do I have to start looping it all in order to make my models?

Resources