Search code examples
phplaravel-4modelsrelationships

Get the user name based on the id in Laravel


i'm trying to show a first name of a user, but i just have a user's id.

My relationships are:

//TypeCost
    public function user()
    {
        return $this->hasMany('User');
    }



  //User
        public function type_cost()
        {
            return $this->belongsTo('TypeCost', 'type_cost_user');
        }

This line show me User's Id, but I need the name.

<td>{{ $type_cost->user_id}}<br>

I hope your help, thanks in advance.


Solution

  • In the TypeCost model hasMany relationship returns an object of type Collection, you have 2 options, using first or tour the object using foreach, also in the User model the relationship belongsToMany returns an object of type Collection, here you can see an example:

    {{ $type_cost->user->first()->username }}
    

    or

    @foreach($type_cost->user as $user)
       {{ $user->username }}
    @endforeach