Reputation: 47
maybe this is a simple problem but for me, am I newbie in Laravel, it's problem, so I have three table
Articles, User, Comments. They have this relationship
In page http://localhost/users/{user_name}
I want to get all articles and all comments that belongs to this user.
Three Model looks like this:
User
public function articles()
{
return $this->hasMany('App\Article');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
Article
public function user()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
and
Comment
public function user()
{
return $this->belongsTo('App\User');
}
public function article()
{
return $this->belongsTo('App\Article');
}
My Controller Show method looks like this:
public function show(User $user)
{
$user->with(['comments','articles'])->get();
return view('users.show', compact('user', 'comments', 'articles'));
}
In view I have everything what I need
{{ dump($user) }}
{{ dump($user->articles) }}
{{ dump($user->comments) }}
{{ dd() }}
and with foreach I get needed attributes, but how do I create link where I can see link to article and comment to her
@foreach($user->comments as $comment)
<div class="block">
//article title
<div><a href="{{ url('articles', $comment->articles->title) }}"></a></div>
<div>{{ $comment->comment }}</div>
@endforeach
To show article I use title of article, not ID.
Thanks
Upvotes: 1
Views: 583
Reputation: 47
I resolved this issue, updated my controller:
public function show(User $user)
{
$params = Comment::where('user_id', $user->id)->get()
return view('users.show', compact('user', 'params'));
}
It's works like I need but I think that there are better way to resolve this.
Upvotes: 0
Reputation: 35370
First, 'comments'
and 'articles'
here don't do anything.
return view('users.show', compact('user', 'comments', 'articles'));
As for the link,
<a href="{{ url('articles', [ $comment->article ]) }}">{{ $comment->article->title }}</a>
Upvotes: 0