-2

trying to make a photo upload but It gives me the following error, even though it worked a while back! what is should I change? I am using larval 5.4

FatalThrowableError Call to a member function getClientOriginalName() on null

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

    public function uploadPhoto(Request $request){

        $file = $request->file('pic');
        $filename = $file->getClientOriginalName();

        $path ='public/img';

        $file->move($path,$filename);
        $user_id = Auth::user()->id;

        DB::table('users')->where('id',$user_id)->update(['pic' => $filename]);
        return back();
    }
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Have you included `enctype="multipart/form-data"` in your form? Failure to do so will not provide you the file you are expecting. – Lionel Chan Dec 06 '17 at 09:42
  • did you change the name for the input `` – JoshKisb Dec 06 '17 at 09:42
  • Looks like your upload did not came through. You need to check if `$request->file('pic')` returns `null` or `UploadedFile`. If null, you should throw an error. However, something is wrong with your upload in HTML. Maybe show the upload Code. – common sense Dec 06 '17 at 09:44
  • looks like a problem with 'pic', have you got {!! Form::file('pic', null) !!}? – Zdenek Machek Dec 06 '17 at 09:44
  • `Call to a member function getClientOriginalName() on null` is a major hint that there's no file upload coming with that name. Sharing the controller code does not help since the problem is not here. – apokryfos Dec 06 '17 at 09:51
  • @Uzeyir Chalabi you should accept Tiger's answer if it solves your issue, ideally he was first to answer your issue – M Khalid Junaid Dec 06 '17 at 10:03
  • @CBroe how is this an "exact" duplicate of that post? – lagbox Dec 06 '17 at 13:22

2 Answers2

0

It seems like in your request the file does not exist, You may determine if a file is present on the request using the hasFile method:

if ($request->hasFile('pic')) {
    //
}
TIGER
  • 2,864
  • 5
  • 35
  • 45
0

Try using Input facade to check if your request has file object

use Illuminate\Support\Facades\Input;

$file = $request->file('pic');
if (Input::hasFile('pic')) {
    $filename = Input::file('pic')->getClientOriginalName();
   // .. rest of the code
}
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • why ... `$request` is the current request .. which is what the `Input` facade uses as its root – lagbox Dec 06 '17 at 09:44
  • @lagbox i posted another possibility (not to duplicate the answer) as for using `$request` Tiger has already posted as an answer before me – M Khalid Junaid Dec 06 '17 at 09:47
  • you could use `Request`, `Input`, `$request`, `request()`, `app('request')` etc etc .. because they are all Request ... that was what i was pointing out :) – lagbox Dec 06 '17 at 09:54