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

kokurate's avatar

How to obtain data from another table using foreign key in Table User

I have three tables users, fakultas and jurusan_prodi. There is a foreign key inside of users, which links it to the fakultas &jurusan_prodi table.

I want to obtain the users data in my view using logged in users auth()user()

Before using the Foreign Key, to get the data I just simply doing like this

    `auth() ->user->fakultas `

And

   Auth() ->user->jurusan_prodi

I'm already add their relationship in each of the model and i'm using laravel 8

How to get their data? I have try something like this but still not work

 auth() ->user() ->fakultas_id->nama;

 auth->user() ->jurusan_prodi->nama
0 likes
1 reply
LaryAI's avatar
Level 58

You can use the Eloquent ORM to query the related data from the other tables. For example, if you have a User model and a Fakultas model, you can define a relationship between them in the User model like this:

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

Then, you can query the related data from the Fakultas table using the auth()->user() method like this:

$fakultas = auth()->user()->fakultas;

You can also use the with() method to eager load the related data when querying the User model:

$user = User::with('fakultas')->find(auth()->id());

You can read more about Eloquent relationships in the Laravel documentation.

Please or to participate in this conversation.