18 Jun, 2017

Call To A Member Function GetClientOriginalName() On String - Laravel File Upload

1 Answer         12717 Views

Jiwan Thapa
18 Jun, 2017

First of all, you need to know that while uploading an image or a file, you are sending an array of data. If you treated it like other usual text input fields, only the file name which is actually a string will be sent via the form to the processing blocks of codes. In that case, the function GetClientOriginalName() can't be executed as the string won't have any additional information. So, make sure you have added the form attribute enctype="multipart/form-data" in the form tag which looks like:


If you used the var_dump() function to dump the value of the input type="file" without adding enctype="multipart/form-data" the result will simple be the file name as a string. If you dumped it with the form attribute enctype="multipart/form-data" the result will appear as shown below in application built on basic php script.

Array ( 
	[upload] => Array ( 
		[name] => test.png 
		[type] => image/png 
		[tmp_name] => C:\xampp\tmp\php9834.tmp 
		[error] => 0 
		[size] => 481933 

Dump the value of the input type="file" in laravel and the result will appear as shown below.

private 'originalName' => string 'test.png'
private 'mimeType' => string 'image/png'
private 'size' => int 481933
private 'error' => int 0	

The function GetClientOriginalName() is used to retrieve the file's original name at the time of upload in laravel and that'll only be possible if the data is sent as array and not as a string.

Hence, you must add enctype="multipart/form-data" whenever you are creating a form with input fields for files or images.

Another important thing is to set the default value of the data table field for file to null to avoid additional issues when no file is selected. And, don't forget to check if the file field is empty with hasFile() function as well

if ($request->hasFile('image')){ 
   // processing codes 

137 Likes         0 Dislike         0 Comment        

Leave a comment