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

vinubangs's avatar

How to fetch record from three table in laravel eloquent

I have four tables

jobposts:

id | user_id | cat_id | job_title

1  |   1     |   1    | job 1
2  |   1     |   2    | job 2
3  |   2     |   3    | job 3
4  |   1     |   3    | job 4

categorymasters:

id | category_name

1  |   cat1 
2  |   cat2  
3  |   cat3  
4  |   cat4 

lastsubcategoryselectedbycompanies:

id | jobposts_id | lastsubcategorymasters_id

1  |   1     |   1 
2  |   1     |   2 
3  |   2     |   3  
4  |   1     |   3 

lastsubcategorymasters:

id | LastSubCategoryName

1  |   lastsubcat1  
2  |   lastsubcat2  
3  |   lastsubcat3  
4  |   lastsubcat4 

jobposts have unique rows. lastsubcategoryselectedbycompanies is mapping of jobposts and lastsubcategorymasters.

Now if any user is login with their credentials (EX: take user_id->1 in jobposts). Now I need to show LastSubCategoryName in comma separated from lastsubcategorymasters table, by jobposts, lastsubcategoryselectedbycompanies and lastsubcategorymasters tables.

allpostedjob.blade.php is:

@foreach($jobposteddetails as $jobposteddetail)
    <tr>
     <td>{{ $jobposteddetail->job_title }}</td>
    </tr>
@endforeach

cotroller is:

public function index()
    {
        $user = Auth::user();
        $jobposteddetails = jobpost::with('categorymaster')->where('user_id', '=', $user->id)->get();
        return view('jobprovider.allpostedjob', compact('user','jobposteddetails'));
    }

jobpost.php model is:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class jobpost extends Model
{
    function categorymaster()
     {
          return $this->belongsTo(categorymaster::class, 'cat_id');
     }
}

It is working proper.

But I need to also show LastSubCategoryName by tables jobposts, lastsubcategoryselectedbycompanies and lastsubcategorymasters.

function lastsubcategory()
     {
          return $this->belongsTo(lastsubcategoryselectedbycompanies::class);
     }

It is not working. How can I fetch my result?

0 likes
1 reply
jlrdw's avatar
jlrdw
Best Answer
Level 75

How about Google

site:laracasts.com 3 tables

Or

site:laracasts.com three tables

you will be surprised at all the answers.

Please or to participate in this conversation.