2016-05-08 4 views
1

Я хочу создать стену пользователя, где все его сообщения будут загружены теми, кто дал комментарий под ним. Поэтому я определил следующие отношения в моей модели User.PHP Laravel foreach

public function post() 
{ 
    return $this->hasMany(Post::class); 
} 
public function comment() 
{ 
    return $this->hasMany(Comment::class); 
} 

Мои сообщения Модель:

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 
public function post_comment() 
{ 
    return $this->hasMany(Comment::class); 
} 

Мой комментарий модель:

public function user() 
{ 
    return $this->belongsTo(User::class); 
} 
public function post() 
{ 
    return $this->belongsTo(Post::class); 
} 

В моем контроллере:

public function wall($id) 
{ 
    $all_post = Post::where('user_id',$id)->get(); 
    return view('client.wall',['all_post'=> $all_post]); 
} 

в моем файле клинка:

@foreach($all_post as $post) 
Post Title: {{ $post->title }} //gets the title properly 
@foreach($post->post_comment as $comment) //this foreach loop throwing erros 
Name: {{ $comment->user->name }} 
Comment: {{ $comment->description }} 
@endforeach 
@endforeach 

Возможно, моя логика неправильно загружать комментарии из базы данных. Потому что я получаю ошибки.

+2

Вы можете добавить ошибки, которые вы получаете на свой вопрос? – Brett

+0

Ki build korteso tawsif bhai? XD –

ответ

1

попробовать эту долю рекламы, если вы по-прежнему есть ошибка

контроллер

public function wall($id) 
{ 
    $all_post = Post::where('user_id',$id)->with('post_comment')->get(); 
    return view('client.wall')->with('all_post',$all_post); 
} 

VIEW

@foreach($all_post as $post) 
Post Title: {{ $post->title }} //gets the title properly 
    @foreach($post->post_comment as $comment) 
    Name: {{ $comment->user->name }} 
    Comment: {{ $comment->description }} 
    @endforeach 
@endforeach 
Смежные вопросы