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

artonico's avatar

Parsing data from multiple tables to a view

Hello.

I'm new to Laravel and have stuck on something that supposed to be simple but i can't find the solution for it. I want to display a transaction record which take data from 2 other table. The parsed data is like this :

[
    {
        "id": 1,
        "user_id": 1,
        "product_id": 1,
        //some other data
    },
    {
        "id": 2,
        "user_id": 1,
        "product_id": 3,
        //some other data
    }
]

The 'user_id' and 'product_id' is taken from other 2 table, users and products in particular. I want to also display the use name which is located in the user table and the product name which is located in the product table on top of the transaction details.

I really appreciate it if you can help me.

0 likes
3 replies
cbaswell's avatar
Level 6

You first want to set up the proper eloquent relationships in your Transaction model...

public function user()
{
    return $this->belongsTo('App\User');
}

public function product()
{
    return $this->belongsTo('App\Product');
}

Then in your controller, eager load the relationships when querying the transaction.

$transactions = Transaction::with('user', 'product')->get();

Then for each transaction you can get the product name and user name.

$transaction->user->name;

$transaction->product->name;

You can find more information in the Laravel documentation.

artonico's avatar

Oh damn that seems so easy that i felt stupid all of a sudden. Thanks a bunch !

willvincent's avatar

@artonico That seems to be a recurring theme when working with Laravel, at least I've noticed it as such.. things end up being easier than it seems like they should be. :D

Please or to participate in this conversation.