I'm trying to pull multiple images and display them from a database table multi_image
which have foreign keys that link to a row in table posts
Each row in the posts
table is linked to one user but a user can have many posts 1:M relationship
Each row in post
can have multiple pictures (up to 4 images maximum) but a picture can only belong to one post 1:M again
PostsController.php
<?php
namespace App\Http\Controllers;
use App\Multi_image;
use App\Post;
use App\User;
use DB;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use function Sodium\compare;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function show(\App\Post $post)
{
$postId = $post->id;
$mImage = DB::table('multi_image')->where('post_id', $postId)->pluck('image');
$postsIm = Post::whereIn('id', $mImage)->paginate(5);
return view('posts.show', compact('post', 'mImage'));
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function images()
{
return $this->hasMany(Multi_image::class);
}
}
Multi_image.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Multi_image extends Model
{
protected $table = "multi_image";
public function post()
{
return $this->belongsTo('App\Post', 'post_id');
}
}
show.blade.php
@foreach($mImage as $image)
<div class="details_image">
<div class="details_image_thumbnails d-flex flex-row align-items-start justify-content-between">
<div class="details_image_thumbnail" data-image=""><img src="{{ URL::to('/') }}/images/{{$image }}" alt=""></div>
</div>
</div>
@endforeach
</div>
<div class="col-5">
<img src="{{ URL::to('/') }}/images/{{$mImage->first() }}" class="w-100">
</div>
.
.
.
posts posts table
multi_image multi_image table
SOLUTION
Question has been corrected with working code
Specific code that made it work: Review show() in PostsController.php
It's undefined because you've not defined it anywhere. Try using App\Multi_image::all() as $image
in your foreach.
Also, your Model Classes seem to have wrong names. You should have called them MultiImage
etc. - singular form, and tables in DB in plural - multi_images
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.