How to join three table by laravel eloquent model

How to join three table by laravel eloquent model

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

Stefan Bogdanescu

Founder & Senior Architect

Merging Three Tables in Laravel Eloquent

You are currently handling a classic relational data retrieval scenario: fetching articles enriched with category names and user details. While your raw SQL query using DB::table works perfectly, it bypasses the expressive power of Eloquent relationships. In Laravel, joining multiple tables isn't about chaining separate joins; it's about defining how your models interact within the application layer.

To achieve this without writing raw queries, you must first ensure your model definitions reflect the actual database schema. Based on your provided tables, you have a many-to-one relationship between articles and categories, as well as articles and users. The foreign keys are clearly defined: articles.categories_id points to categories.id, and articles.user_id points to users.id.

You need to define these relationships in your respective models. Assuming you have an Article model, a Category model, and a User model, the logic resides entirely within the Article model because it holds the foreign keys. Open your app/Models/Article.php file and add the following relationship methods:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    // Relationship to Category
    public function category()
    {
        return $this->belongsTo(Category::class, 'categories_id');
    }

    // Relationship to User
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

Notice the second argument in belongsTo. Laravel defaults to looking for a column named category_id and user_id. Since your schema explicitly uses categories_id, you must pass that string to the constructor. This step is critical; without it, Eloquent will look in the wrong columns or fail silently if using strict modes.

Once these relationships are defined, you can replace your raw SQL with a fluent query builder approach. You don't need to manually join tables for simple select operations involving related data. Instead, you can use eager loading. This technique tells Eloquent to fetch the related records in a single database query (via an internal JOIN) and attach them to the main collection.

Here is how you would rewrite your query:

use App\Models\Article;

$articles = Article::with(['category', 'user'])
    ->get();

This returns a collection of Article models. Each model now has a populated $category and $user property containing the full objects, not just IDs. To access the data exactly as your SQL query did—returning a flat array—you can iterate over the collection or use toArray() with specific keys if needed.

If you specifically need to return only certain columns while still joining the data (similar to your raw select statement), you can combine eager loading with column selection:

$articles = Article::with(['category', 'user'])
    ->get()
    ->map(function ($article) {
        return [
            'id' => $article->id,
            'title' => $article->title,
            'body' => $article->body,
            'username' => $article->user->user_name ?? null, // Adjusted to match your schema column name
            'category_name' => $article->category->category_name ?? null, // Adjusted to match your schema column name
        ];
    });

Alternatively, you can use the select method alongside eager loading if you are using Laravel 10 or later, where Article::with(['category', 'user'])->get(['id', 'title', 'body']) allows you to specify columns while still eager-loading relationships. Note that in older versions of Laravel, mixing explicit column selection with eager loading requires careful handling, often necessitating the map approach above.

The primary trade-off here is performance and clarity. Eloquent handles the SQL generation internally. When you use with(), it generates a single query for articles and two additional queries (or one optimized JOIN) for the relationships depending on the version and configuration. For large datasets, this is generally more efficient than running multiple separate queries or complex raw joins.

The main pitfall to avoid is accessing null values without checks if you are flattening the data into an array. Since user_name and category_name are not primary keys, ensuring your models have the correct accessor names matching your database columns (e.g., user_name vs username) prevents runtime errors when trying to access $article->user->username. Always verify that the model attribute name matches the database column definition exactly.

Our network