Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

scottsuhy's avatar

Beginner: Having trouble understanding how to extract the data out of a result from a query.

I am new to Laravel/Eloquent and I'm having trouble understanding how to extract the data out of a result from a query.

I'm calling the following query in the controller

$purchase['purchase_price_total_LY'] = DB::table('coins')
		->select(DB::raw('SUM (purchase_price) as purchase_price_total_LY'))
		->where('user_email', '=', auth()->user()->email)
		->whereBetween(DB::raw('DATE(purchase_date)'), [$range_lastyr_start, $range_lastyr_end])
		->get();

and passing the result back to the view in the return as follows:

		return view ('pages.financials', compact('user', 'purchase'));

In the view:

<td>Purchase Price:</td><td><a> {{$purchase['purchase_price_total_LY']}}</a></td>

The result in the view is this:

[{"purchase_price_total_ly":"37"}]		

When I do a dd($purchase, $purchase['purchase_price_total_LY']); I see the following:

array:1 [▼
  "purchase_price_total_LY" => Illuminate\Support\Collection {#548 ▼
    #items: array:1 [▼
      0 => {#547 ▼
        +"purchase_price_total_ly": "37"
      }
    ]
  }
]
Illuminate\Support\Collection {#548 ▼
  #items: array:1 [▼
    0 => {#547 ▼
      +"purchase_price_total_ly": "37"
    }
  ]
}

What's the most appropriate way to extract the 37 out of the array in the view?

0 likes
3 replies
Sti3bas's avatar
Sti3bas
Best Answer
Level 53

@scottsuhy as far as I understand you want to get the first result, so try to change ->get(); to ->first()->purchase_price_total_LY; in your controller.

jlrdw's avatar

Why use an array, use object.

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name;
scottsuhy's avatar

You guys are great!

I changed the controller query to use "->first()" and change the variable

        $purchase_price_total_LY = DB::table('coins')
			->select(DB::raw('SUM (purchase_price) as purchase_price_total_LY'))
			->where('user_email', '=', auth()->user()->email)
			->whereBetween(DB::raw('DATE(purchase_date)'), [$range_lastyr_start, $range_lastyr_end])
			->first();
	```

then changed the return to this:
```		
return view ('pages.financials', compact('user', 'purchase_price_total_LY')

Then in the view I changed to this:

<tr><td>Purchase Price:</td><td><a>{{$purchase_price_total_LY->purchase_price_total_ly }}</a></td>

and now i have an answer of 37.

thank you. after 2 hours of trying several attempts (and learning a lot) you provided great advice.

Please or to participate in this conversation.