bhhussain's avatar

Upload file error if empty

I am using the below code to upload a file.. If I select the file to upload, it is working fine but If i did not select a file then it is throwing error message

Call to a member function getClientOriginalName() on null

My Code

if($request->th_attach->getClientOriginalName())
        {
            $ext = $request->th_attach->getClientOriginalExtension();
            $file = date('YmdHis').rand(1,99999).'.'.$ext;
            $request->th_attach->storeAs('public/categories',$file);
        }    
        else
        {
            $file='';
        }

In some case I can not upload files.

0 likes
7 replies
Nakov's avatar

There is a method on the request which will tell you if a file has been attached:

$request->hasFile('th_attach');

Then get the file using

$request->file('th_attach');
1 like
Nakov's avatar

@bhhussain did the above fixed the issue? You should resolve the questions after someone gives you a solution.

bhhussain's avatar

Sorry... it is not yet resolved.. I tried your code in different combination but it did not work.

Nakov's avatar
Nakov
Best Answer
Level 73

@bhhussain this should do it:

$filename='';

if( $request->hasFile('th_attach'))
{
    $file = $request->file('th_attach');
    $ext = $file>getClientOriginalExtension();
    $filename = date('YmdHis').rand(1,99999).'.'.$ext;
    $file->storeAs('public/categories', $filename);
}

// file here should be set to the full path ie: "public/categories/$filename"

Let me know :)

bhhussain's avatar

If I did not attach a file then no error message but If I attach a file then I am getting the below error

Call to undefined function App\Http\Controllers\Admin\getClientOriginalExtension()

Nakov's avatar

Sorry, I missed the dash here, try this instead:

$ext = $file->getClientOriginalExtension();
bhhussain's avatar

Thank you very much.. It is working fine..

Please or to participate in this conversation.