How to use foreign key when querying from two tables

How to use foreign key when querying from two tables

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Querying Across Foreign Keys in Laravel and SQL

When designing a database schema, establishing relationships between tables is fundamental. In your specific scenario, you have two distinct entities: vehicles and users. The vehicles table stores car models like "VW", while the users table holds personal details such as names and phone numbers. The bridge connecting these datasets is the foreign key constraint. Specifically, the car_owner column in the vehicles table references the primary key user_id in the users table.

To retrieve a list of all Volkswagen cars alongside their owners' contact information, you need to join these two tables. If you simply query the vehicles table using a standard SELECT statement, you will only get the car models and owner IDs. You will miss the actual names and phone numbers because that data resides in a different physical location within your database. The foreign key is not just a constraint; it is the mechanism that allows you to traverse from the vehicle record to the user record.

In raw SQL, this operation requires an explicit JOIN. Without the JOIN clause, the database engine treats the tables as isolated silos. To populate the HTML output you described—echoing the car model, owner name, and phone number—you must instruct the database to match rows where vehicles.car_owner equals users.user_id.

Here is how you would construct that query in standard SQL:

SELECT 
    vehicles.car_model,
    users.user_name,
    users.user_phone
FROM 
    vehicles
JOIN 
    users ON vehicles.car_owner = users.user_id
WHERE 
    vehicles.car_model = 'VW';

The JOIN keyword is critical here. If you use an INNER JOIN, the result set will only contain records where a match exists in both tables. This is usually the desired behavior for displaying owner details; if a vehicle record exists but has no matching user (perhaps due to a deleted account), you might prefer to exclude that row or handle it differently.

In the context of Laravel, which likely powers your application given the mention of laravelcompany.com, you do not write raw SQL strings for these queries. Instead, you leverage Eloquent relationships to keep your code semantic and maintainable. You should define a relationship in your Vehicle model that tells Eloquent how to find the associated user.

First, update your Vehicle model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Vehicle extends Model
{
    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'car_owner');
    }
}

Notice the belongsTo relationship. This is appropriate because multiple vehicles can belong to a single user, but each vehicle belongs to exactly one user (based on your schema). The method name owner gives semantic meaning to the code, making it clear that this field points to the owner's data.

Once the relationship is defined, you can access the user details effortlessly:

$vwCars = Vehicle::where('car_model', 'VW')->with('owner')->get();

foreach ($vwCars as $vehicle) {
    echo "Car model: {$vehicle->car_model}<br>";
    echo "Car owner: {$vehicle->owner->user_name}<br>";
    echo "Contacts: {$vehicle->owner->user_phone}<br>";
}

The with('owner') clause is an eager loading mechanism. Without it, Laravel would execute a separate query for every single vehicle to fetch the owner's data, leading to the infamous N+1 query problem. By specifying the relationship in the get() call, Laravel generates a single efficient query with a JOIN underneath, fetching all necessary data in one go.

It is worth noting that while you can manually construct SQL queries using DB::table() or raw strings, relying on Eloquent relationships ensures your application adapts automatically if you change column names or table structures later. The foreign key logic remains abstracted away, allowing you to focus on the business logic of displaying car inventories and owner contacts.

Our network