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

BJBT99's avatar

Image Upload in Laravel 7

Hey guys I have been stuck on this for a few days now so hopefully someone can give me some sort of insight.

So I am trying to be able to upload an image for a specific store. When I upload the image the page simply refreshes and the file won't be in DB or project structure.

Here is my controller:

<?php

namespace App\Http\Controllers;

use App\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class SuperadminStoresController extends Controller
{
    /**
     * SuperadminStoresController constructor.
     */
    public function __construct()
    {
//        $this->middleware('IsSuperAdmin');
    }

    public function index()
    {
        $stores = Store::get();

        return view('superadmin.stores.index', compact('stores'));
    }

    public function update(Request $request)
    {
        $values    = request('stores');
        $store_ids = array_keys($values);
        $stores    = Store::whereIn('id', $store_ids)->get();

        foreach ($stores as $store)
        {

            if ($request->hasFile('logo_path')) {
                $logo = $request->file($values[$store->id]['logo_path']);
                $extension = $logo->getClientOriginalExtension();
                $storedName = $logo . '.' . $extension;
                Storage::disk('public')->put($storedName,  File::get($logo));
            } else {
                $storedName = null;
            }

            $store->update([
                'twilio_number' => $values[$store->id]['twilio_number'],
                'logo_path' => $values[$store->id]['logo_path'],
            ]);

//
//            if ($request->hasFile($values[$store->id]['logo_path'])) {
//                $fileNameWithExt = $request->file($values[$store->id]['logo_path'])->getClientOriginalName();
//                $fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//                $extension = $request->file($values[$store->id]['logo_path'])->getClientOriginalExtension();
//                $storedName = $fileName . '.' . $extension;
//                Storage::putFileAs('/storage/uploaded_files/logos',
//                    $request->file($values[$store->id]['logo_path']), $storedName);
//            } else {
//                $storedName = null;
//            }
        }

        return redirect()->back();
    }
}

The commented out section in the foreach above was something I tried but didnt have any luck in. Left it there just in case.

Here is my filesystems.php public driver where I am trying to store the image:

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

And I have a stores DB that I have a field logo_path where I am attempting to save the file path. Any help would be greatly appreciated let me know if I can give any more information!

0 likes
30 replies
laracoft's avatar

@bjbt99

Not sure why you are re-writing public but the filesystem.php path should be storage/app/public/uploaded_files/logos

root of storage/app/public/uploaded_files/logos links to url of https://domain.com/storage/uploaded_files/logos

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

1 like
BJBT99's avatar

Yes I have that in my form. This is the table data for the file upload as well

  		<td>
                        <input type="file"
                               id="logo"
                               name="stores[{{ $store->id }}][logo_path]"
                               accept="image/png, image/jpeg, image/jpg">
               </td>
                    	
laracoft's avatar

@bjbt99 restore your public in filesystems.php to

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

and show the list of values for $storedName?

BJBT99's avatar

So I guess the other issues when I put the following in my if statement for request() and in my $store->update() I get undefined index: logo_path

$values[$store->id]['logo_path']

Sorry for the newbie questions if they are I am very new to laravel 7 and everything behind it

BJBT99's avatar

How would I go about giving you that? You want my html from browser or just my blade file??

BJBT99's avatar

Thanks for clarifying I wasn't aware of that term!

    <form method="POST" action="http://ripemetrics.test/superadmin/stores/update" accept-charset="UTF-8" enctype="multipart/form-data"><input name="_token" type="hidden" value="ENrko4tlYJ909lMUAqVeODQqQ1mjkJFZGeDvSs9d">
    <input type="hidden" name="_token" value="ENrko4tlYJ909lMUAqVeODQqQ1mjkJFZGeDvSs9d">    <table>
        <thead>
            <th>Store</th>
            <th>Twilio Number</th>
            <th>Upload File</th>
            <th>Current Logo</th>
        </thead>
        <tbody>
                            <tr>
                    <td>Pineapple Express</td>
                    <td>
                        <input type="text"
                               name="stores[30][twilio_number]"
                               placeholder=""
                               value="15805805552"
                        >
                    </td>
                    <td>
                        <input type="file"
                               id="logo"
                               name="stores[30][logo_path]"
                               accept="image/png, image/jpeg, image/jpg"
                        >
                    </td>
                    <td>
                                                    <p>/private/var/tmp/phpAqsdKR</p>
                                            </td>
                </tr>
                            <tr>
                    <td>PE #2</td>
                    <td>
                        <input type="text"
                               name="stores[31][twilio_number]"
                               placeholder=""
                               value="15805805554"
                        >
                    </td>
                    <td>
                        <input type="file"
                               id="logo"
                               name="stores[31][logo_path]"
                               accept="image/png, image/jpeg, image/jpg"
                        >
                    </td>
                    <td>
                                                    <p>No Logo Uploaded!</p>
                                            </td>
                </tr>
                    </tbody>
    </table>
    <input class="saas-button" type="submit" value="Update">
    </form>

In that middle p tag is the output of what I get if I upload a file now with the disk set to what you asked me to change it to. Unsure of why the path is structured like so.

/private/var/tmp/phpAqsdKR
laracoft's avatar

@bjbt99

Must use such a complicated name for your file? name="stores[30][logo_path]"

Able to simplify? See if this helps

$logo = $request->file("stores[{$store->id}][logo_path]");
$extension = $logo->getClientOriginalExtension();
$storedName = "{$logo->getClientOriginalName()}.{$extension}";
Storage::disk('public')->put("uploaded_files/logos/{$storedName}", File::get($logo->getPathname()));
BJBT99's avatar

So if you look in the controller I am trying to be able to be store specific. I have this to query in my controller

$values    = request('stores');
        $store_ids = array_keys($values);
        $stores    = Store::whereIn('id', $store_ids)->get();

and then this in my blade

stores[{{ $store->id }}][logo_path]

AND also this in my controller

$values[$store->id]['logo_path']

Just so I can be store specific about the file upload and twlo number and what not. If there is a better way I am open to suggestions

BJBT99's avatar

Sorry I totally didnt see your suggestion let me implement and let you know how it is! @laracoft

laracoft's avatar

@bjbt99

try

$logo = $request->file("stores[{$store->id}][logo_path]");
$extension = $logo->getClientOriginalExtension();
$storedName = "{$logo->getClientOriginalName()}.{$extension}";
Storage::disk('public')->put("uploaded_files/logos/{$storedName}", File::get($logo->getPathname()));
BJBT99's avatar

yeah so sadly still having the undefined index: logo_path issue talking about the line with my if statement. @laracoft

laracoft's avatar

@bjbt99 oh... ok

  if ($request->hasFile("stores[{$store->id}][logo_path]")) {
1 like
BJBT99's avatar

So that got rid of the initial issue but now its same issues on the logo_path on the store update method called

 $store->update([
                'twilio_number' => $values[$store->id]['twilio_number'],
                'logo_path' =>  $values[$store->id]['logo_path']
            ]);
laracoft's avatar

@bjbt99

	    $store->update([
                'twilio_number' => $values[$store->id]['twilio_number'],
                'logo_path' => "uploaded_files/logos/{$storedName}",
            ]);
laracoft's avatar

@bjbt99

Were any files saved under storage/app/public/uploaded_files/logos?

laracoft's avatar

@bjbt99

Change the code below and show what happens when you submit a form with an image

public function update(Request $request)
{
    dd(reset($request->files->all()));
    ...
}
laracoft's avatar

@bjbt99

That means you have no files being submitted from the browser at all. Are you submitting JPG and PNG only?

1 like
BJBT99's avatar

Okay so I die dumped the image upload and it gave me

array:1 [▼
  30 => array:1 [▼
    "logo_path" => Symfony\Component\HttpFoundation\File\UploadedFile {#37 ▼
      -test: false
      -originalName: "pineappleexp.jpg"
      -mimeType: "image/jpeg"
      -error: 0
      path: "/private/var/tmp"
      filename: "php1PK2Ri"
      basename: "php1PK2Ri"
      pathname: "/private/var/tmp/php1PK2Ri"
      extension: ""
      realPath: "/private/var/tmp/php1PK2Ri"
      aTime: 2020-10-12 11:38:48
      mTime: 2020-10-12 11:38:48
      cTime: 2020-10-12 11:38:48
      inode: 16572254
      size: 35398
      perms: 0100600
      owner: 501
      group: 0
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
    }
  ]
]
laracoft's avatar

@bjbt99

Move dd(reset($request->files->all()));, inside the $request->hasFile().

Does it still die dump?

If the image could not be saved you should get some exception.

BJBT99's avatar

This is the code I put it in for the dump at the beginning of my update function

	$array = $request->files->all();
        dd(reset($array));

This is the result when I move it to the $request->hasFile():

array:1 [▼
  30 => array:1 [▼
    "logo_path" => Symfony\Component\HttpFoundation\File\UploadedFile {#37 ▼
      -test: false
      -originalName: "pineappleexp.jpg"
      -mimeType: "image/jpeg"
      -error: 0
      path: "/private/var/tmp"
      filename: "php70i0fZ"
      basename: "php70i0fZ"
      pathname: "/private/var/tmp/php70i0fZ"
      extension: ""
      realPath: "/private/var/tmp/php70i0fZ"
      aTime: 2020-10-12 11:51:49
      mTime: 2020-10-12 11:51:49
      cTime: 2020-10-12 11:51:49
      inode: 16572787
      size: 35398
      perms: 0100600
      owner: 501
      group: 0
      type: "file"
      writable: true
      readable: true
      executable: false
      file: true
      dir: false
      link: false
    }
  ]
]
laracoft's avatar

@bjbt99

If code goes into hasFile() then the following ought to work. Make sure you have a folder storage/app/public/uploaded_files/logos

$logo = $request->file("stores[{$store->id}][logo_path]");
$extension = $logo->getClientOriginalExtension();
$storedName = "{$logo->getClientOriginalName()}.{$extension}";
Storage::disk('public')->put("uploaded_files/logos/{$storedName}", File::get($logo->getPathname()));
1 like
BJBT99's avatar

Yeah I have the proper folder structure but still no luck sadly. It just uploads the file path of /uploaded_files/logos to the DB. Thank you for the help ill have to keep working at it. If you have any more suggestions anything is appreciated thanks again!

Please or to participate in this conversation.