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

YuraLons's avatar

Images upload for post

Good afternoon. I would like to know how to properly configure the controller so as to load multiple images for the post. Now the controller looks like this:

public function storePosts(Request $request)
    {
       $imagesLoad = Blog::create([
        'title' => $request->title,
        'slug' => $request->slug,
        'description' => $request->description,
        'categories_id' => $request->categories_id,
    ]);

    if ($request->hasfile('images')) {
        $images = $request->file('images');

        foreach($images as $image) {
            $name = $request->file('images')->getClientOriginalName();
            $path = Storage::putFile('images', $request->file('images'));

            Images::create([
                'name' => $name,
                'path' => $path
              ]);
        }
    }
        dd($imagesLoad);
    }

. When I upload files and check which fields were filled in via the dd command, I do not find the filled image field. The project has three tables Blog, Images_blog, Images Blog Migration:

$table->id();
$table->unsignedBigInteger('categories_id');
$table->foreign('categories_id')
      ->references('id')
      ->on('categories')
      ->onDelete('cascade');
$table->string('title');
$table->string('slug');
$table->text('description');
$table->timestamps();

Images Migration:

$table->string('name')->nullable();
$table->string('path')->nullable();

Images_Blog Migration:

$table->integer('images_id');
$table->integer('blog_id');

Model Images looks like this:

protected $table = 'images';
    protected $fillable = ['name', 'path'];

    public function imageForBlog()
    {
        return $this->belongsToMany(Blog::class);
    }

The Blog model looks like this:

public function images()
    {
        return $this->belongsToMany(Images::class);
    }

Laravel himself does not give any errors when loading, he specified a new array for the blog in the file system, so that when loading the files when creating a post, they fall into the post folder. Here is the filesystems code:

'blog' => [
'driver' => 'local',
'root' => storage_path('app/public/blog'),
'url' => env('APP_URL').'/storage',
'visibility' => 'blog',
        ],

How to make sure that when creating a post, the file is dropped with the name of the post, and entered into the database with the name and path to the image?

0 likes
7 replies
dev_kassimi's avatar
$name = $image->getClientOriginalName();
$path = Storage::putFile('images', $image);
dev_kassimi's avatar
foreach ($request->file('images') as $file) {
        $filename  time() . '.' . $file->getClientOriginalExtension();
        $path = "images/".$filename;
                try {
                    Storage::disk('local')->put($filename, $path);
                    $image = new Image();
                    $image->name = $filename;
                    $image->path =  $path;
                    $image->save();
                } catch (Exception $e) {
                    dd($e);
                }
}
YuraLons's avatar

@dev_kassimi

App\Models\Blog {#282 ▼
  #table: "blogs"
  #fillable: array:4 [▼
    0 => "title"
    1 => "slug"
    2 => "description"
    3 => "categories_id"
  ]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #escapeWhenCastingToString: false
  #attributes: array:7 [▼
    "title" => "123"
    "slug" => "123"
    "description" => "123123123"
    "categories_id" => "1"
    "updated_at" => "2021-11-16 20:52:41"
    "created_at" => "2021-11-16 20:52:41"
    "id" => 5
  ]
  #original: array:7 [▼
    "title" => "123"
    "slug" => "123"
    "description" => "123123123"
    "categories_id" => "1"
    "updated_at" => "2021-11-16 20:52:41"
    "created_at" => "2021-11-16 20:52:41"
    "id" => 5
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
YuraLons's avatar

I changed the code to this

 foreach( $blog->images as $image ) {
        if ($request->hasFile('images')) {

            $request->file->store('blog', 'public');

            $image = new \App\Models\Images([
                'name' => $request->get('name'),
                'path' => $request->file->hasName(),
            ]);
            $image->save();
        }
    }
    dd($blog);

, now there are relations

#dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "images" => Illuminate\Database\Eloquent\Collection {#291 ▼
      #items: []
      #escapeWhenCastingToString: false
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []

, but the files are not loaded into the images table, not into the blog_images table The form contains all the necessary tags CreateForm

<form action="{{ route('***.blog.store') }}" method="post" enctype="multipart/form-data" >
@csrf

        <div class="border rounded py-2 mb-2">
            <label for="title">Title</label>
            <input type="text" name="title" id="title" class="title">
        </div>

        <div class="border rounded py-2 mb-2">
            <label for="image">Images</label>
            <input type="file" id="image" name="image[]" multiple />
        </div>

        <div class="border rounded py-2 mb-2">
            <button class="bg-red-700 text-white py-2 px-4 rounded uppercase" type="submit">Save</button>
        </div>


    </form>
YuraLons's avatar

@dev_kassimi Unfortunately, no, the result is still empty, and the files are not downloaded, well, that is, usually when you download something, a status bar appears at the bottom of the browser with the processing of the download and the page is loaded a little longer because of this, but it still loads like usually there is no bar status.

YuraLons's avatar

That is, as I wrote above, I need the images themselves (their name and path to them) to get into the Images table The blog was created in its own table Blog But also the rows in the Blog_Images table were created. In this error, you can see that it calculates the field in the image table, but there they simply are not there, so there are fields indicating the name of the downloaded file, as well as its path

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'images.blog_id' in 'where clause' (SQL: select * from `images` where `images`.`blog_id` = 8 and `images`.`blog_id` is not null)

Please or to participate in this conversation.