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

Niely's avatar
Level 1

Foreign key relation laravel

Hi

I need to do the following, I have two tables: PRODUCT

+----+----------------+----------------------------------------------------------+---------------------------------+--------------+
| id | name           | description                                              | image                           | categorie_id |
+----+----------------+----------------------------------------------------------+---------------------------------+--------------+
|  1 | 3M Scotchal 50 | Gekleurde polymeer vinyl 5j houdbaarheid (lange termijn) | /images/print/products/none.png |            3 |
+----+----------------+----------------------------------------------------------+---------------------------------+--------------+

And ORDERS

+----+------------+--------+-------+-------+---------+------+
| id | product_id | amount | times | price | user_id | paid |
+----+------------+--------+-------+-------+---------+------+
|  1 |          1 |     10 |     3 |   105 |       1 |    0 |
|  2 |          1 |     10 |     2 |    70 |       1 |    0 |
|  3 |          1 |     10 |     2 |    70 |       1 |    0 |
|  4 |          1 |     10 |     1 |    35 |       1 |    0 |
|  5 |          1 |     10 |     1 |    35 |       1 |    0 |
|  6 |          1 |     10 |     3 |   105 |       4 |    0 |
+----+------------+--------+-------+-------+---------+------+

I need to get the name from the product table, by using the foreign key (product_id) in the orders table. This is my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use Auth;

class BasketController extends Controller
{
    public function index() {
        $orders = DB::table('orders')
        ->where([
            ['user_id', Auth::user()->id],
            ['paid', 0]
        ])
        ->select('id', 'product_id', 'amount', 'times', 'price')
        ->get();

        $products = DB::table('products')
        ->select('id', 'name')
        ->get();

        return view('basket')
        ->with('orders', $orders)
        ->with('products', $products);
    }
}


I don't now how to only select from products where product_id from $orders matches. How to do it? Thanks!

0 likes
3 replies
Snapey's avatar

Have you something against Models and relationships?

The 'eloquent way' would be

public function index() {

   $orders = Order::with('product')
        ->where('user_id',Auth::user()->id)
        ->where('paid', false)
        ->get();

    return view('basket')->with('orders', $orders);

}

a bit more readable isn't it ?

Niely's avatar
Level 1

Yes, but where are my model-files located?

Snapey's avatar

You have to make them.

Start with the Laravel from scratch series. Its free and will cover all the basics.

1 like

Please or to participate in this conversation.