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

mohammedkamar's avatar

Calling data from foreign key but when I show data to blade, instead of name of the student it shows the id of that table even after i join the tables in laravel.

public function index(){

    $books = DB::table('libraries')->join('students','libraries.stu_id','=','students.id')->select('libraries.*','students.name')->get();
    $students = DB::table('students')->select('*')->get(); // To get Student List from Students table
    return view('db.index' , compact('students','books'));

}
0 likes
5 replies
mohammedkamar's avatar

@foreach ($books as $book)

Book_id: {{$book->id}} Student Name: {{$book->stu_id}} | Book Name: {{$book->book}} | Status: {{$book->status}} | Delete

@endforeach

1 like
tisuchi's avatar
tisuchi
Best Answer
Level 70

@mohammedkamar Update your query like this:

$books = DB::table('libraries')
           ->join('students', 'libraries.stu_id', '=', 'students.id')
           ->select('libraries.*', 'students.name as student_name')
           ->get();

Now update your blade:

@foreach ($books as $book)
    Book_id: {{ $book->id }}
    Student Name: {{ $book->student_name }} | 
    Book Name: {{ $book->book }} | 
    Status: {{ $book->status }} | 
    <a href="{{ route('deleteBookRoute', $book->id) }}">Delete</a>
@endforeach
3 likes
mohammedkamar's avatar

@tisuchi Oh my god! Thanks a lot. It worked as I wanted, Thank you so much, sir. I appreciate it. Is it possible for you can tell me the logic behind it? Again Thanks sir i have been trying for almost 5 hours

2 likes
tisuchi's avatar

@mohammedkamar Good to know that it solves your issue.

What I did do here actually?

$books = DB::table('libraries')
           ->join('students', 'libraries.stu_id', '=', 'students.id')
           ->select('libraries.*', 'students.name as student_name')
           ->get();

I've aliased the student's name as student_name. Therefore, in the Blade foreach loop, I should access this aliased name instead of the stu_id.

@foreach ($books as $book)
    Book_id: {{ $book->id }}
    Student Name: {{ $book->student_name }} | 
    Book Name: {{ $book->book }} | 
    Status: {{ $book->status }} | 
    <a href="{{ route('deleteBookRoute', $book->id) }}">Delete</a>
@endforeach

In the loop, I just called as {{ $book->student_name }} which will display the name of the student.

2 likes

Please or to participate in this conversation.