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

SarahS's avatar
Level 12

Adding query results to view

I have an EntityController and the index method gets all the Entities and sends them to the view where I display them in a table.

I have then created a basic SQL query to get a sum of all the Bills (one to many relationship) for each Entity. How do I then add this or pass this across to the Index view in order to show the total amount of Bills for each Entity in my table?

This is what I have so far:

    public function index()
    {
		// new bit that gets my SUM of bills
        $result = DB::select('SELECT entity_id, SUM(amount) FROM bills GROUP BY entity_id;');

        return view('app.entities.index')
            ->with('entities', Entity::all());
    }

I don't know if this is the best way of getting the SUM value but I looked around the docs etc. and couldn't see any alternatives.

So, is there a better way of getting the SUM and how do I pass that in with my Entity?

0 likes
2 replies
SarahS's avatar
Level 12

Thank you, that's perfect and thanks for adding the link.

Please or to participate in this conversation.