简体   繁体   中英

Laravel Eloquent: How to replace id with name

I have following models and controller.

User.php

public function reporting() 
{
    return $this->hasMany('App\Reporting','user_id','id');
}

RegisterController.php

public function viewUsers()
{

    $users = User::with('reporting')->get();

    return view('users',compact('users'));
 }

users.blade.php

@foreach($users as $user)
        <tr>
            <td>{{$user->name}}</td>
            <td>
                @foreach($user->reporting as $report)
                {{$report->reporting}}
                @endforeach
            </td>
        </tr>
    @endforeach

the above code retursn

name                                  Reporting Person
========================================================
Ankur /*gets from user table*/          35 //gets from reporting table

the name of reporting person is Yadav and this name is in users table how i replace the Reporting person id 35 to name Yadav in view

According to our discussion

In users table you have two columns id, name and in reportings table you have user_id, reporting

Now add this in your Reporting table

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

Then in your view inside you parent foreach add this

@foreach ($report->user as $reportinguser) 
 {{ $reportinguser->name}} 
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM