Search code examples
laravel-5controllerdatatablesinner-joinlaravel-blade

I want to display a column from 2 tables Laravel


I have 2 tables:

teachers and users I want to display for each teacher the name of users who is the same teacher.

I know in controller it can be done maybe with inner join:

$users= DB::table('teachers')
->select('name')
->join('users', 'users.id', '=', 'teachers.id')
->get();  

but in blade template i don't know how to display for each teacher, when i do this

<a class="ahref" href={{route('users')}}> <div class="blueDecor">

         <p style="text-transform: uppercase;"> {{$teacher->name}} </p>

        </div>
    </a>

and when for the {{route('users')}} :

   @foreach($users as $user)

{{$user->name}}

@endforeach

and here show for all teachers appears all of users

for example Teachers: when i click on Theodor to display Anna, Maria.

Theodor -----------------------> Users: Anna, Maria

Alexander----------------------> Users: Sofia, Alex, Patrick

Sarah--------------------------> Users: Rick, George

please help me:(


Solution

  • You need to use the laravel relationships to achieve this In your case it will be one to one relationship between the 2 Models (users and teachers).

    Please go through the below link https://laravel.com/docs/5.6/eloquent-relationships#one-to-one

    You will need to define relation in both the models. Say for Example your

    user table Model name is Users

    teachers table Model name is Teachers

    Create one relation in User

    public function UserTeacher()
    {
     return $this->hasOne("\App\Models\Teachers","id","id");
    }
    

    Create one relation in Teachers

    public function TeacherUser()
    {
     return $this->hasOne("\App\Models\Users","id","id");
    }
    

    You can access the data like below

    $data = Users::with('UserTeacher')->get();
    

    Pass the $data variable to blade file and access it like :

    {{$data->UserTeacher->name}}
    

    I have tried to create example based on the limited data available in you question, You can change it accordingly.