在我的网站上,注册用户可以查看其他用户的帖子。这些帖子可以有多个图片。图像名称存储在图像表中,并具有post_id作为外键,以便知道图像的用途。图像名称存储在图像表中,实际图像存储在存储文件夹中。我的问题是,当我尝试使用循环检索所有并显示与帖子相关的图像时,出现以下错误。
ErrorException (E_ERROR)
Property [cover_image] does not exist on this collection instance. (View: C:\xampp\htdocs\eventcw\resources\views\viewmore.blade.php)
这是我的Post模型图像功能:
public function images()
{
return $this->hasMany('App\Image');
}
这是我的Image模型帖子功能:
public function images()
{
return $this->hasMany('App\Image');
}
以下是我的观点:
@foreach($post->images->cover_image as $image)
<div class="row">
<div class="col-md-12">
<img style="width: 700px; height: 500px;" src="{{ asset('storage/cover_images/' . $post->images->cover_image) }}">
</div>
</div>
@endforeach
这是加载视图的控制器方法:
public function getMore($post_id){
$post = Post::where('id', $post_id)->firstOrFail();
return view ('viewmore', ['post' => $post]);
}
这是我的帖子和图片迁移:
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->enum('type', array('sport','culture','other'));
$table->string('subtype');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('cover_image');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->timestamps();
});
答案 0 :(得分:2)
您收到此错误是因为在您的foreach循环中
使用src="{{ asset('storage/cover_images/' . $image->cover_image) }}"
而不是$post->images->cover_image
@foreach($post->images->cover_image as $image)
<div class="row">
<div class="col-md-12">
<img style="width: 700px; height: 500px;" src="{{ asset('storage/cover_images/' . $image->cover_image) }}">
</div>
</div>
@endforeach
其次,您没有使用热切加载获取Post的图像。
$post = Post::where('id', $post_id)->with('images')->firstOrFail();
或者你可以
@foreach($post->images()->get() as $image)
<div class="row">
<div class="col-md-12">
<img style="width: 700px; height: 500px;" src="{{ asset('storage/cover_images/' . $image->cover_image) }}">
</div>
</div>
@endforeach
希望这有帮助