Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mikaelo's avatar

Multiple Images in article - gallery

Hello guys,

I am trying to find best way to deal with images in articles. Lets say I have simple CMS, which allows me to create an article, and then upload/assign multiple images to this article. So basically create a gallery.

Now I know how to work with one image/per one article, but dont know how to work with multiple images. It all starts with database.

Right now I have two tables: articles and images. Do I need to create a third one and then somehow connect everything via Eloquent relationships?

Because the problem is, that the images are not exclusive just for one article, but may be used in more articles. (So it is a different situation compared to article comments for example)

0 likes
20 replies
mstnorris's avatar
Level 55

@hassanjamal it isn't polymorphic in this case, as images only belong to articles and articles have many images (articles can share images, so to speak). Polymorphic relationships are for such situations when a model can belong to more than one other model. Take a comment for example. If you think of Facebook, you can comment on a photo, a video, or a status update etc. Rather than creating three separate comment classes, you have one Comment class which is polymorphic to Photo, Video, and Status. Although this is a crude example, it should go some way to explain its use.

@Mikaelo in your case a simple Many To Many relationship will do the trick.

Article model

public function images() {
    return $this->belongsToMany('App\Image'); //  or whatever your namespace is
}

Image model

public function articles() {
    return $this->belongsToMany('App\Article'); //  or whatever your namespace is
}

article_image table

Set up a pivot table, you can do this manually or use @JeffreyWay's Laravel 5 Extended Generators Package.

You'd need to use make:migration:pivot Article Image and this will set it up for you. Or, if you'd want to, you can do it manually by creating a new migration. It should look like this:

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticleImageTable extends Migration {

    public function up()
    {
        Schema::create('article_image', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('article_id')->unsigned()->index();
            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->integer('image_id')->unsigned()->index();
            $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('article_image');
    }

}

This will create a simple table:

| id | article_id | image_id |
|----|------------|----------|
| 1  | 1          | 2        |
| 2  | 2          | 1        |
| 3  | 2          | 2        |
| 4  | 3          | 1        |
| 5  | 3          | 3        |

Article(1) has one Image(1)
Article(2) has two Images(1,2)
Article(3) has two Images(1,3)

ArticlesController controller

In your ArticlesController or whatever it is called you'd need to do something like the following. I'm sure this will make sense to you now.

<?php namespace App\Http\Controllers;

use App\Article;

class ArticlesController extends Controller
{

    public function index()
    {
        $articles = Article::with('images')->get();

        return view('articles.index', compact('articles')); // whatever your view is called
    }

    public function show($id)
    {
        $article = Article::find($id);

        $article->load('images');

        return view('articles.show', compact('article')); // whatever your view is called
    }

}

I hope this has cleared things up for you, if you have any questions or would like me to explain things further, just shout.

6 likes
Mikaelo's avatar

mstnorris: Thank you for your detailed answer. Getting totally lost here though :). Isn’t there an easier way? For example I know how to do this with comments, but it is much easier, because they belong to only certain article. So you can have just table: articles and then a second table: comments.

Now with images, it is more difficult since the same images can be used in multiple articles, so it seems to me I need third table?

SCC's avatar

Define easy? Because I thought what @mstnorris just gave you was the simplest option.

1 like
Mikaelo's avatar

So I have done everything mstnorris suggested. Now what do I need to do next? I somehow need to retrieve something in my controller and then show the images in my view right? :)

Mikaelo's avatar

Hello guys. Any help help? As I said, everything is set up exactly as mstnorris suggested. Now I don’t know how to return these data in controller and show them in view :/. Thank you

mstnorris's avatar

@Mikaelo I'm on holiday at the moment, will take a look Thursday evening when I'm back at my desk.

Mikaelo's avatar

mstnorris: Thank you so much. Looking forward :)

PalTamasWBA's avatar

@Mikaelo In the controller try this

$articles = Article::with('images')->get();

return view('yourview', compact('articles', $articles));

Hope this works, if not i'm sorry, i'm new to Laravel.

dcdamianchase's avatar

Sorry for the old bump, however I was just implementing this approach into my website and was wandering how to approach the pivot table.

The pivot table needs both the article id and image id in order to create the connection.

So I have created two separate upload forms, one for article and another for the image.

What is the best practice to retrieve the ids for both article and image and assign the image to the article in front end?

imoh's avatar

@mstnorris please is there any tutorial out there that shows every step in this to post an article with multiple images or can u continue with the image controller and the view

imoh's avatar

@mstnorris i have followed your explanation step by step but my problem is how to save the article with the image, like how will i continue from where u stopped?

i first created a form like this

{{csrf_field()}} Title
<div class="form-group">
    <label for="exampleFormControlFile1">Example file input</label>
    <input type="file"  name="file[]"  class="form-control-file">
</div>


<div class="form-group">
    <label for="exampleFormControlTextarea1">content</label>
    <textarea class="form-control"  name="article"   rows="5" placeholder="enter your content"></textarea>
</div>


    <button  class="btn btn-primary"  >Submit Post</button>

i know how to store image and article separately on my database but in this case since i am creating the article and images together, how do i store both of them,

That is how will my controller look like to store the method? and how will i display it in my view

Thank you very much for your help

imoh's avatar

@mstnorris i please can you do the store method in the controller if i am saving the images from a form input field..... and also how to display the images with the article on my view

Please or to participate in this conversation.