Search code examples
phpeloquentmodelslaravel-5

Three tables in Laravel 5 with help Eloquent models


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 enter image description here

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() }}

enter image description here

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


Solution

  • 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.