-1

I have a table called "logs" with custom column "auth_id" and i have another table called "users" with same column name "auth_id" and column "username".

How can i take it from "logs" with "logs.auth_id" and get username by "users" table?

Now i'm getting results by:

$match->messages = DB::table('logs')->where('match_id', '=', $match->match_id)->get();

Blade:

@foreach ($match->messages as $message) 

{{ $message->auth_id }}: 
{{ $message->message }}

Example: Now i'm getting AUTH5556 with {{ $message->auth_id }} but i need to get USERNAME from "users" table by {{ $message->auth_id }}

Abolfazl Mohajeri
  • 1,734
  • 2
  • 14
  • 26

2 Answers2

1

Don't use joins, this is the whole reason for using something like laravel (eloquent). You need to define a relationship between your models.

On your user model you would define a method

public function logs()
{
    return $this->hasMany(Log::class);
}

On your log model

public function user()
{
    return $this->belongsTo(User::class);
}

Now you need to make sure on your logs table you have a user_id column.

Now you can simply get the log for example

$log = Log::find($id);

And you can retrieve any information about the user who owns that log, for an example in a blade file.

{{ $log->user->username }}

To get reverse information you need to iterate through the results as the user can have many logs. Eg:

$user = User::find($id);

Then you'd do something like this in your blade

@foreach($user->logs as $log)
    {{ $log->column_on_log_you_want }}
@endforeach

You also need to look into eager loading.

This is what makes laravel so clean and nice to use.

Read through the documentation

Colin Barstow
  • 552
  • 2
  • 12
  • Hi, Colin. I agree with you that I should mention Laravel ORM at the first place. But I don't agree that using Laravel Query Builder and `JOIN` is a bad way. In some cases performance overhead created by ORM is not acceptable and QB works just fine. ORM is not the holy grail but just another tool which can make developer life easier in some situations. – Ivan Vartanyan Jun 19 '18 at 13:27
  • For something as simple as this, you'd be silly to use a raw statement. Please read this answer and you will understand that it's non-beneficial in nearly all circumstances https://stackoverflow.com/a/47139799/7272910 – Colin Barstow Jun 19 '18 at 20:40
-1

You need to use JOIN in your query to get username from users table. Here is the link to Laravel manual