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

YuraLons's avatar

How to combine data when creating a post?

There are three tables, Images, Blog, ImagesBlog. When creating a blog post, I additionally transfer the image to the second tab.

 public function storePosts(Request $request)
    {
    $blog = Blog::create([
        *****CODE***
    ]);

     foreach( $request->file('images') as $image) {

         $name = $image->getClientOriginalName();
         $path = $image->store('public');

            $image = new \App\Models\Images([
                'name' => $name,
                'path' => $path,
            ]);
            $image->save();
        }
    $blog->images = new \App\Models\BlogsImages([
        'blog_id' => $blog->id,
        'images_id' => $image->id,
    ]);
    $blog->images->save();
        dd($blog);
    }

All data are perfectly reflected and stored in the database. But how can I make it so that when creating a post, in the BlogImages table, the IDs of the uploaded images and the post ID are added? I tried to do it, but it didn't work, I thought to transfer from $block->id and from images $image->id

0 likes
3 replies
tykus's avatar

This looks like a many-to-many relation rather than needing a BlogImage model

MichalOravec's avatar
Level 75

Create many to many relationship betwen your models.

Don't forget to add validation.

public function storePosts(Request $request)
{
    $blog = Blog::create([
        // columns
    ]);

    $images = collect([]);

    foreach ($request->file('images') as $image) {

        $images->push(Images::create([
            'name' => $image->getClientOriginalName(),
            'path' => $image->store('public')
        ]));
    }

    $blog->images()->attach($images->pluck('id'));
}

Docs: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many and https://laravel.com/docs/8.x/eloquent-relationships#updating-many-to-many-relationships

Please or to participate in this conversation.