У меня есть система, в которой есть users
, которые создают сообщения, и они также могут комментировать posts
.
Вот миграции:
users
таблица
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('gender')->default('Male');
$table->string('email')->unique();
$table->string('city')->default('Peshawar');
$table->string('avatar')->default('user.png');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
posts
стол
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('p_id');
$table->text('description');
$table->integer('user_id'); // this should be user id nothing else
$table->timestamps();
});
}
comments
стол
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id'); // who has done comment
$table->integer('post_id'); // on which post comment has been done
$table->text('body');
$table->timestamps();
});
}
Модели
User
Модель
class User extends Authenticatable{
use Notifiable;
// custom function used for relationshisp
// user can have many posts
public function posts(){
return $this->hasMany('App\Post');
}
// user can have many comments as well
public function comments(){
return $this->hasMany('App\Comment');
}
}
Post
Модель
class Post extends Model{
// posts belongs to one user
public function user(){
return $this->belongsTo('App\User');
}
public function comments(){
return $this->hasMany('App\Comment');
}
}
Comment
Модель
class Comment extends Model
{
// doing this we could insert data into comment table
protected $fillable =['user_id','post_id','body'];
// we need two(2) relations here
// relation of comment with post
// relation of comment with user
// 1. комментарий принадлежит одному сообщению
public function post(){
return $this->belongsTo('App\Post');
}
// 2. комментарий также принадлежит пользователю
public function user(){
return $this->belongsTo('App\User');
}
}
route
Route::get('/home', 'HomeController@index')->name('home');
Вот метод index
в HomeController
public function index(){
$posts = Post::with('comments')->get();
// $comments = Comment::all();
return view('home')->with( array('posts'=>$posts ) );
}
Проблема
Итак, когда я посещаю /home
Я хочу получить все сообщения с их комментариями .
Как вы можете видеть, я получил posts
с их comment
следующим образом:
$posts = Post::with('comments')->get();
А потом я передаю его home.blade.php
.Вот что я делаю в home.blade.php
, чтобы выполнить эту задачу.
Просмотр /home.blade.php
@foreach($posts as $post)
<h4 class="media-heading">{{$post->user->name}}</h4>
<small>{{$post->created_at}}</small>
<p>{{$post->description}}</p>
<!-- trying to retrieve comments with each post -->
@if (count($post->comments))
@foreach($post->commnents as $comment)
<small>$comment->body</small>
@endforeach
@else
No comments Found
@endif
@endforeach
Это дает мне эту ошибку
Неопределенная переменная: post (View: F: \ application \ resources \ views \ home.blade.php)
С учетом этих models
и их relationships
с каждымдругой, я делаю это неправильно, чтобы получить комментарии для каждого сообщения?Если так, как я могу получить все posts
с их comments
, а когда нет comments
, должно быть сказано: no comments found
.
Вот каков результат, возвращаемый dd($posts)
dd ($ posts), возвращающий это , посмотрите на пустое поле для комментариев.
На вкладке network
отображается следующее
Пожалуйста, помогитеСпасибо всем.