Parajuli Sunil
Parajuli Sunil

Reputation: 57

How to retrieve user name from user table by using data (user_id) from another table having relationship

I have two models

User.php

public function opportunities()
{
    return $this->hasMany('App\Opportunity');
}

Opportunity.php

public function user()
{
    return $this->belongsTo('App\User');
}    

I have user_id column in opportunities table and inserted user id (from user table using Auth) every time user posts record.

Now i need a view to return "this post is posted this user".

First I find the post id by

$posts =  Opportunity::find($id);
$posted_by = User::find($posts->user_id);
return view('opportunity.detail')->with('post', $posts, 'posted_by', $posted_by);

I have rendered user name by {{$posted_by->name}}

But I got undefined constant in the view file $posted_by while $post is fine. Am I doing it in right way or not? I am passing two array variable to the post and its not working. Any help will be appreciated.

Upvotes: 3

Views: 2254

Answers (2)

Erast Stinca
Erast Stinca

Reputation: 1

You can put this

public function getUserName() {
 return User::where('id', $this->user_id)->first()->name;
}

in your Opportunity.php model and call it in you view

@foreach ($posts as $post)
  {{ $post->getUserName() }}
@endforeach

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

Your controller could look like:

return view('opportunity.detail', [
    'post' => Opportunity::find($id);
]);

In the view to show user name:

Post {{ $post->title }} posted by {{ $post->user->name }}

https://laravel.com/docs/5.5/eloquent-relationships#relationship-methods-vs-dynamic-properties

If for some reason you want to use ->with(), do this:

->with(['post' => $posts, 'posted_by' => $posted_by]);

Or:

->with('post', $posts)->with('posted_by', $posted_by); 

Upvotes: 3

Related Questions