Search code examples
laravelimageblogslaravel-5.6

How can I get images under a blog for a user


What I actually want is, for a specific user, I'm trying to show every image under a single blog. What I'm getting is a single blog post images for every blog.

Controller

$user_id = Session::get('id');
$user = Users::find($user_id);
$blogs = Blog::where('user_id', $user_id)->paginate(10);
$blogImage = BlogImage::where('blog_id', $blogs->pluck('id'))->get();


return view('Users.userlayout', compact('user', 'blogCat', 'blogs', 'username', 'blogImage'));

View Page

@foreach($blogs as $blog)
    <div class="post">

        @foreach($blogImage as $img)
            <img src="{{asset('storage/blog_img/'.$img->blog_img)}}" alt="Image"
                 class="img-responsive">
        @endforeach

        <p>
            <?php $str = $blog->blog_desc; ?>
            {{str_limit($str, 250, "...")}}
        </p>
        <a href="{{URL::to('/blog-details/'.$blog->id)}}" target="_blank" class="btn_1">
            Read more
        </a>
    </div>
    <hr>
@endforeach

Solution

  • This is because you're using where instead of whereIn.

    If you try and pass an array or a collection to where it will only use the first value.

    $blogImage = BlogImage::whereIn('blog_id', $blogs->pluck('id'))->get();
    

    Since this will return all of the BlogImage's associated with the Blog's the in the paginated list I would imagine you'll need to do a check to make sure you're only displaying the images that are associated with the specific Blog. One way you can do this is by using `@continue():

    @foreach($blogImage as $img)
    
        @continue($blogImage->blog_id !== $blog->id)
    
        <img src="{{asset('storage/blog_img/'.$img->blog_img)}}" alt="Image" class="img-responsive">
    
    @endforeach
    

    All of that being said I would recommend using a one-to-many relationship between Blog and BlogImage:

    Blog

    public function images()
    {
        return $this->hasMany(BlogImage::class);
    }
    

    BlogImage

    public function blog()
    {
        return $this->belongTo(Blog::class);
    }
    

    Then in your controller you can Eager load the images and have something like:

    $blogs = Blog::with('images')->where('user_id', $user_id)->paginate(10);
    

    And your blade file would have:

    @foreach($blog->images as $image)
    
        <img src="{{asset('storage/blog_img/'.$image->blog_img)}}" alt="Image" class="img-responsive">
    
    @endforeach
    

    You could then apply the same one-to-many relationship logic between User and Blog as well.