I'm trying to do some data transformation through Laravel collection
in my application for graphs. I want to create labels
and datasets
I'm having a data something like this:
[
{
"id": 1,
"company_id": 1,
"year": 25,
"turnover": "3449",
"profit": "3201",
"turnover_range": 25,
"financial_year": {
"id": 25,
"year": "2024-25"
}
},
{
"id": 2,
"company_id": 1,
"year": 33,
"turnover": "5616",
"profit": "5905",
"turnover_range": 25,
"financial_year": {
"id": 33,
"year": "2032-33"
}
},
{
"id": 3,
"company_id": 1,
"year": 1,
"turnover": "4309",
"profit": "8563",
"turnover_range": 175,
"financial_year": {
"id": 1,
"year": "2000-01"
}
},
{
"id": 4,
"company_id": 1,
"year": 14,
"turnover": "5936",
"profit": "8605",
"turnover_range": 25,
"financial_year": {
"id": 14,
"year": "2013-14"
}
},
{
"id": 5,
"company_id": 1,
"year": 29,
"turnover": "7156",
"profit": "3844",
"turnover_range": 75,
"financial_year": {
"id": 29,
"year": "2028-29"
}
},
{
"id": 6,
"company_id": 1,
"year": 6,
"turnover": "5868",
"profit": "633",
"turnover_range": 75,
"financial_year": {
"id": 6,
"year": "2005-06"
}
},
{
"id": 7,
"company_id": 1,
"year": 25,
"turnover": "5809",
"profit": "6831",
"turnover_range": 575,
"financial_year": {
"id": 25,
"year": "2024-25"
}
},
{
"id": 8,
"company_id": 1,
"year": 12,
"turnover": "1",
"profit": "1976",
"turnover_range": 25,
"financial_year": {
"id": 12,
"year": "2011-12"
}
},
{
"id": 9,
"company_id": 1,
"year": 30,
"turnover": "680",
"profit": "1222",
"turnover_range": 25,
"financial_year": {
"id": 30,
"year": "2029-30"
}
},
{
"id": 10,
"company_id": 1,
"year": 26,
"turnover": "8197",
"profit": "3687",
"turnover_range": 25,
"financial_year": {
"id": 26,
"year": "2025-26"
}
}
]
Which is coming from eloquent collection of my model:
$fRA = FinancialAndRisk::whereHas('company', function($q) use($request){
$q->where('slug', $request->slug);
})
->with('financialYear')
->get();
I want to pluck out all the year
inside financial_year
as labels so i tried:
$labels = $fRA->pluck('financial_year.year');
it is showing null.
Again I tried
$labels= $fRA->map(function ($item){
$item->fin_year = $item->financial_year['year'];
return $item;
})->pluck('fin_year');
Even if I do transform I am getting the same null result,
Any ideas appreciated. Thanks
Edit:
Data format to be something like this:
labels = ['2000-01','2032-33','2024-25','2005-06'];
You should just be able to do something like:
$labels = $fRA->map(function ($item) {
return $item->financial_year->year;
})->unique();
Obviously, remove unique()
if you want to include the duplicates (if there are any).
Alternatively, if you have the hasMany
relationship set up in your FinancialYear model and you don't need $fRA
after this you could just do:
$labels = FinancialYear::whereHas('FinancialAndRisk.company', function ($query) use($request) {
$query->where('slug', $request->slug);
})->pluck('year');