Get the top value of array - php

Context: To give context, I am trying to create a graph with the months as the labels and the number of applications as the dataset.
My code:
$apps = Application::whereBetween('created_at', [
Carbon::now()->startOfYear(),
Carbon::now()->endOfYear(),
])
->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('M');
})
->toArray();
returns
array:3 [▼
"Jan" => array:2 [▶]
"Feb" => array:1 [▶]
"May" => array:1 [▶]
]
I want to create an array that produces this result:
['Jan', 'Feb', 'May']
I have tried using array keys, values, etc without any joy.

If you are looking for only month list then you can use selectRaw and groupBy in query
$apps = Application::whereBetween('created_at', [
Carbon::now()->startOfYear(),
Carbon::now()->endOfYear(),
])->selectRaw('MONTHNAME(created_at) as month,count(*) as total')
->groupBy('month')
->pluck('total','month')->toArray();
For getting months and count list separately
array_keys($apps) and array_values($apps)

Related

How to display pagination links in a blade on Laravel 8?

I need to add pagination, but it seems complicated in my case, because I get data from database with paginate, but then I modify this data and when I call links() method on the blade, I get the following exception
Method Illuminate\Support\Collection::links does not exist.
My code in the Controller method:
$transactionsByLastMonth = Transaction::where('created_at', '>=', Carbon::now()->subDays(30)->toDateTimeString())
->where('user_id', Auth::user()->id)
->with(['user', 'propertyFrom', 'propertyTo', 'paddockFrom', 'paddockTo', 'cattleTypeFrom', 'cattleTypeTo'])
->paginate(10);
$transactionsByDays = collect(TransactionResource::collection($transactionsByLastMonth))
->sortByDesc('created_at')
->groupBy(function($date) {
return Carbon::parse($date['created_at'])->format('d');
});
return view('user.reports.index', compact('transactionsByDays'));
Yes, a pagination limits my data to 10 rows, but due to I'm grouping data by days, my collection modifies itself and I can't use $transactionsByDays->links() method to show pagination.
If see dd($transactionsByDays) , it looks like:
Illuminate\Support\Collection {#1381 ▼
#items: array:3 [▼
"01" => Illuminate\Support\Collection {#1019 ▼
#items: array:7 [▼
0 => array:16 [▶]
1 => array:16 [▶]
2 => array:16 [▶]
3 => array:16 [▶]
4 => array:16 [▶]
5 => array:16 [▶]
6 => array:16 [▶]
]
}
31 => Illuminate\Support\Collection {#1386 ▼
#items: array:2 [▼
0 => array:16 [▶]
1 => array:16 [▶]
]
}
30 => Illuminate\Support\Collection {#1384 ▼
#items: array:1 [▼
0 => array:16 [▶]
]
}
]
}
Therefore I need to paginate all arrays together which inside "01", 31, 30...
How can I do it?
Maybe rewrite code above in the controller somehow?
The main aim is that I need to group data to every day according to my json-resource class.
Any ideas?
I've found a solution gyus. I had to pass also a variable transactionsByLastMonth and use links() method over this.
In the meantime I use foreach on the my blade file over transactionsByDays variable. It's correctly works together cause it uses the same data from database, just in the first case its not filtered and not grouped and in the second one it is.
return view('user.reports.index', compact('transactionsByLastMonth', 'transactionsByDays'));

Result query to single array of string

I would like to transform the result of an Eloquent query into a single array of strings.
What my query currently gives:
(I apply a ->toArray() to initial query to get that :)
array:2 [▼
0 => array:1 [▼
"title" => "User"
]
1 => array:1 [▼
"title" => "Premium"
]
]
What I would like it to give me:
['User', 'Premium'];
My query :
Rank::where('strength', '<', $this->rank->strength)->select('title')->get();
Thanks in advance
You can use pluck():
Rank::where('strength', '<', $this->rank->strength)->pluck('title');
If you want exactly same array response instead of collection, You can add toArray() function at the last
$ranks = Rank::where('strength', '<', $this->rank->strength)
->pluck('title')->toArray();

Laravel working with nested collection delete nested branch

unable to delete all nested branches where "product" => null
Have a query
$cartWhere['user_id'] = $user_id;
$cartWhere['site_id'] =$currentSite->id;
$item = Cart::select('product_id','quantity')->with(['product' => function($product) use ($search){
$product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
$product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
},'product.manufacturer:id,name'])
->where($cartWhere)->get();
then I receive collection that has all filtered carts but some of these carts have a relation with product => null
1 => App\Models\Cart {#736 ▼
...
#original: array:2 [▼
"product_id" => 1
"quantity" => 2
]
...
#relations: array:1 [▼
"product" => App\Models\Product {#785 ▶}
]
}
2 => App\Models\Cart {#736 ▼
...
#original: array:2 [▼
"product_id" => 2
"quantity" => 2
]
...
#relations: array:1 [▼
"product" => null
]
}
sorry for my English
You can filter them from the results using the collections filter() method
$item = Cart::select('product_id','quantity')
->with(['product' => function($product) use ($search) {
$product->join('product_translations', 'products.id', '=', 'product_translations.product_id');
$product->where( 'product_translations.name', 'LIKE','%'.$search.'%');
}, 'product.manufacturer:id,name'])
->where($cartWhere)
->get()
->filter(function ($cart) {
return $cart->product !== null;
});
Along with with you should use whereHas. So the result will not include any relation with null value. So this way you can also avoid the extra filter method used.

Eloquent request with subitems count

I have 2 tables :
Valuechains : id, created_at, updated_at, deleted_at
Segments : id, valuechain_id (Foreign key), created_at, updated_at, deleted_at
And pivot tables (not really important here).
I have a method with sql requests ...
$valuechains list gives me a list of all the value chains which are not (soft) deleted
$valuechainCount counts the number of valuechains which are published
$segmentCount counts the number of segments for each value chains
I try to use the map function in order to add a column which contains the number of segments for each value chains ...
public function vcListAndSegmentCount() {
$valuechainLists = Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->get();
$valuechainCount = Valuechain::whereNull('valuechains.deleted_at')->count();
for ($i=0; $i < $valuechainCount; $i++) {
$segmentCount[$i] = Segment::whereNull('segments.deleted_at')
->where('valuechain_id', '=', $valuechainLists[$i]->id)->count();
}
$valuechainLists = $valuechainLists->map(function ($record) use ($segmentCount) {
$vclists = array_first($segmentCount, function ($value, $key) use ($record) {
return $value['id'] === $record['valuechain_id'];
});
$record['count'] = $vclists;
return $record;
});
dd($valuechainLists);
}
The map methods adds a column my output collection. Unfortunatelly, the new collection is not giving me the right numbers of segments for each value chain... it only adds one value ...
Here is what I obtain :
Collection {#380 ▼
#items: array:4 [▼
0 => Valuechain {#450 ▼
...
#attributes: array:4 [▼
"id" => 1
"vcname" => "Génétique"
"vcshortname" => "Génétique"
"count" => 6
]
#original: array:3 [▶]
...
}
1 => Valuechain {#451 ▼
...
#attributes: array:4 [▼
"id" => 2
"vcname" => "Biotruc"
"vcshortname" => "Biotruc"
"count" => 6
]
...
}
2 => Valuechain {#452 ▼
...
#attributes: array:4 [▼
"id" => 3
"vcname" => "VC3"
"vcshortname" => "VC3"
"count" => 6
]
...
}
3 => Valuechain {#453 ▼
...
#attributes: array:4 [▼
"id" => 4
"vcname" => "VC4"
"vcshortname" => "VC4"
"count" => 6
]
#original: array:3 [▶]
...
}
]
}
I obtain 6, 6, 6 and 6 whereas the count should be 6, 5, 4, 4...
If you are using Laravel >= 5.2 and if you have defined the relationships on the models, you can use the withCount() method.
It would go something like this:
Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->withCount(['segments' => function ($query) {
$query->whereNull('deleted_at);
}])
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->get()
or if your Segment model uses the SoftDeletes trait, then it's a bit simpler:
Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
->withCount('segments')
->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
->where('langs.isMainlanguage', '=', '1')
->whereNull('valuechains.deleted_at')
->get()
add count value as a property instead of array element.
$valuechainLists = $valuechainLists->map(function ($record) use ($segmentCount) {
$vclists = array_first($segmentCount, function ($value, $key) use ($record) {
return $value['id'] === $record['valuechain_id'];
});
$record->count = $vclists;
return $record;
});
I changed
$record['count'] = $vclists;
to
$record->count = $vclists;
Add a reference: &$segmentCount
$valuechainLists = $valuechainLists->map(function ($record) use (&$segmentCount) {....
Also I'm not sure what your array_first function is doing.

Laravel collection pluck dropping a value

I have the following Eloquent query in a Laravel 5.2 project:
$regsByCtryCollection = Organisation::join('countries_currencies', 'countries_currencies.id', '=', 'organisations.country_id')
->select(DB::raw('DISTINCT LCASE(countries_currencies.country_code) AS ctry, COUNT(organisations.id) AS val'))
->groupBy('ctry')
->get();
The raw query produces this output:
ctry val
at 1
au 5
br 1
The Eloquent call produces a collection of three rows (matching raw query output) like this:
Collection {#791 ▼
#items: array:3 [▼
0 => Organisation {#777 ▼
#table: "organisations"
#hidden: []
........
#attributes: array:2 [▶]
#original: array:2 [▼
"ctry" => "at"
"val" => 1
]
#relations: array:5 [▶]
........
}
1 => Organisation {#778 ▶}
2 => Organisation {#779 ▶}
]
}
I then pluck the values and format for Highmaps like this
$regsByCtry = $regsByCtryCollection->pluck('ctry', 'val')->map(function($country, $value) {
return [
"hc-key" => $country,
"value" => $value
];
})->values()->toJson();
And one of the values is dropped and I get this:
[
{"hc-key":"br","value":1},
{"hc-key":"au","value":5}
]
Why is the first entry getting dropped?
{"hc-key":"at","value":1}
I am using this same process with two other Eloquent queries and it works as expected, but just not on this collection.
Additionally, I also sum all the values in the array of objects like this:
$regsTotal = array_sum($regsByCtryCollection->pluck('val')->toArray());
And I get the correct value, including all three records summed:
$regsTotal = 7;
The issue is with pluck('ctry', 'val'). This will return val as key & ctry as value. In your query output at & br has same value 1. So one of it getting replaced by the other one.
Try pluck('val', 'ctry')->map(function($value, $country)
Reference

Categories