How to upload file in Laravel 5

 

Uploading files in laravel is as simple as you upload file in core PHP. Before you upload file to your server, keep in mind which is very very important is that, the form method should be POST, enctype=”multipart/form-data” form attributes must be exist in your form and the folder should be writable where you want to upload your file else file upload will not work. By default PHP use /tmp directory for storing your uploaded files. Laravel has very easy method for file uploading, which I will discussed in this article.

In this tutorial we will see how to insert a demo data into the database and upload the user image as well.
route.php
First we will create our 3 routing methods, get method is for display the form while post method is for uploading the file.
Route::get(‘register’, ‘UserController@register’);
Route::post(‘save_user’, ‘UserController@SaveRegister’);
Route::post(‘store_user’, ‘UserController@SaveRegisterWithMultipleProfile’);

Database table
Below are the user table where we will insert the data and upload user image.

CREATE TABLE IF NOT EXISTS `user` (
  `uid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,  
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `profile_pic` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`uid`)  
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=0 ;

Create “upload” folder
Now create the folder where you want to store the uploaded files. In this example i have created a folder under /public/uploads/user_image

Controller
Now create the controller file name as UserController.php under “app/HTTP/Controllers” folder.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Html\HtmlFacade;
use Validator; 

class UserController extends Controller {
	
	//For Register New User
	public function register(){		
        return view('register');
	}
	
	//For Save New User
	public function SaveRegister(Request $request){		
		if ($request->isMethod('post')){                
                $messages = ['name.required' => 'Please enter your name.',
			 'email.required' => 'Please enter your email.',					 
			 'profile_pic.required' => 'Please upload your profile picture.',
			 'profile_pic.image' => 'Profile picture should be an image.'];				
		
                $validator = Validator::make($request->all(),
                                             ['name'=>'required',
					      'email' => 'required',
					      'profile_pic' => 'required|image'
					     ],$messages);
				
	       if($validator->fails()){
                    return redirect('register')
                        ->withErrors($validator)
                        ->withInput();
                }  
				
				$name=$request->input('name');
				$email=$request->input('email');
                
				//For File Upload
				$user_profile='';
				$UserUploadedImageURL='';
				if($request->hasFile($request->input('profile_pic'))){
					$user_profile=time().'.'.$request->file('profile_pic')->getClientOriginalExtension();
					$NewFilePath=$request->file('profile_pic')->move(public_path('uploads\user_image'), $user_profile);					
				}
				
		DB::table('user')->insert([
                                ['name' => $name,
                                 'email' => $email,
				 'profile_pic' => $user_profile
                                ]
                        ]);
		   return redirect('success')->with('message', 'Thank you for registering with us.');
		}			
	}
}
?>

In the above code we have 2 functions register() and SaveRegister(). register() display the template file whereas SaveRegister() function will call once user will submit the form.

Blade Template File
Earlier I have already discussed, when you will upload file then enctype=”multipart/form-data” form attribute should be there in the form tag. In laravel you just need to add ‘files’=>true attributes in the form array, which will automatically add enctype=”multipart/form-data” attributes into your form. Below are sample user registration form which is located at resources/views/register.blade.php

In the below code the script checks, if there is any validation error then display all the error message to the user and display the registration form.

@if (count($errors) > 0)    
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif

{!! Form::open(array('url' =>'save_user', 'class' => '' ,'method' => 'post','files'=>true)) !!}
	Name: {!! Form::text('name') !!}
	Email Address : {!! Form::text('email') !!} 
	Profile Picture : {!! Form::file('profile_pic') !!}
    {!! Form::submit('Submit') !!}
{!! Form::close() !!}

How to upload multiple files in Laravel?

In the above code we saw how to upload single image and save into the database. But now we will see how to upload multiple image that belongs to user.

Database table
Below are the users_image table where multiple user image will store.

CREATE TABLE IF NOT EXISTS `users_image` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `user_image` varchar(20) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (uid) REFERENCES user(uid)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Controllers
Replace the above code with this one.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Html\HtmlFacade;
use Validator; 

class AnupController extends Controller {
	
	//For Register New User
	public function register(){		
        return view('register');
	}
	
	//For Save New User
	public function SaveRegisterWithMultipleProfile(Request $request){		
		if ($request->isMethod('post')){
                
                $FileData=$request->file('profile_pic'); 
				$TotalFile=count($FileData);
				$ct=0;
				$Arr=array('name'=>'required','email'=>'required');
				$MessageArr=array('name.required' => 'Please enter your name.',
						'email.required' => 'Please enter your email.');
				$image_no=1;//Start Image Number
				while($ct<$TotalFile){
					$Arr['profile_pic.'.$ct]='required|image';//Image should be only jpeg, png, bmp, gif, or svg.';
					$MessageArr['profile_pic.'.$ct.'.required']='Profile picture '.$image_no.' is blank.';
					$MessageArr['profile_pic.'.$ct.'.image']='Image '.$image_no.' should be only jpeg, png, bmp, gif, or svg.';
					$ct++;
					$image_no++;
				}				
				$validator = Validator::make($request->all(),$Arr,$MessageArr);	
				
				if($validator->fails()){
                    return redirect('register')
                        ->withErrors($validator)
                        ->withInput();
                }  
				
				$name=$request->input('name');
				$email=$request->input('email');
                                 /*Insert the data into user table and 
				  get the insert id so we will insert the id into user_pic
				  table*/
				  
				$LastInsertId=DB::table('user')->insertGetId([
                                ['name' => $name,
				'email' => $email
                                ]
                        	  ]);
				
				//For File Upload
				$ArrayFiles=array();
				if($TotalFile>0){
					$ct=0;
					while($ct<$TotalFile){
						if ($request->file('profile_pic.'.$ct)->isValid()){
							if($request->hasFile('profile_pic.'.$ct)){
								$new_file=time().$ct.'.'.$request->file('profile_pic.'.$ct)->getClientOriginalExtension();					
								$NewFilePath=$request->file('profile_pic.'.$ct)->move(public_path('uploads\user_image'), $new_file);
								$ArrayFiles[]=array('user_image'=>$new_file,'uid'=>$LastInsertId);								
							}
						}
					  $ct++;	
					}
				}				
				DB::table('users_image')->insert($ArrayFiles);				
				return redirect('success')->with('message', 'Thank you for registering with us.');
		}			
	}
}
?>

Now in the SaveRegisterWithMultipleProfile() function we are checking all the input file and set error message of every file. If there is no any validation error then, this function will insert the data into user table and store the last insert id into the $LastInsertId variable. Next the script check all the uploaded image one by one, if it is a valid image then store all the image and last insert id into the $ArrayFiles array variable. Because if you will insert the data into your database inside a loop then the script will slow down the website. Instaed store the array data in a variable and then pass the array to the laravel’s insert function.

Blade template file for multiple files upload

@if (count($errors) > 0)    
    <ul>
        @foreach ($errors->all() as $error)
            <li>{{ $error }}</li>
        @endforeach
    </ul>
@endif

{!! Form::open(array('url' =>'store_user', 'class' => '' ,'method' => 'post','files'=>true)) !!}
	Name: {!! Form::text('name') !!}
	Email Address : {!! Form::text('email') !!}
	Profile Picture 1 : {!! Form::file('profile_pic[]') !!}
    Profile Picture 2 : {!! Form::file('profile_pic[]') !!}
    Profile Picture 3 : {!! Form::file('profile_pic[]') !!}
    {!! Form::submit('Submit') !!}
{!! Form::close() !!}

There are many built-in functions of laravel which are related to file uploading. Some functions are given below:

Function Name Description Example
$request->file(‘profile_pic’)->getClientOriginalName(); Returns the original file name. Hydrangeas.jpg
$request->file(‘profile_pic’)->getClientOriginalExtension(); Returns the original file extension. jpg
$request->file(‘profile_pic’)->getClientMimeType(); Returns the file mime type. image/jpeg
$request->file(‘profile_pic’)->guessClientExtension(); Returns the extension based on the client mime type jpeg
$request->file(‘profile_pic’)->getClientSize(); Returns the file size in bytes. 595284
$request->file(‘profile_pic’)->getMaxFilesize(); Returns the maximum size of an uploaded file as configured in php.ini 67108864

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories