Form Validation with File Upload in Laravel 6

How to upload file in Laravel 6: Today, i will show you how to create simple file upload in laravel 6. I write article step by step about image upload in laravel. I also added validation with image upload in laravel. So doing it you can download a fresh laravel file or you can do it in your current running project.

Example of file upload in laravel, we will create two routes one for get method and another for post method. we created simple form with file input. So you have to simple select image and then it will upload in "images" directory of public folder. So you have to simple follow bellow step and get image upload in laravel 6 application.

laravel-6-image-file-upload-with-form-validation

Step 1 : Install Laravel 6

To do it run bellow command in your project directory.

composer create-project --prefer-dist laravel/laravel imageUpload

Step 2: Create Route

In next step, we will add new two routes in web.php file. One route for generate form and another for post method So let's simply create both route as bellow listed:

Route::name('frontend.')->namespace('Frontend')->group(function () {
    Route::get('/user-register', 'Auth\[email protected]')->name('register')->middleware('guest');
    Route::post('/user-register', 'Auth\[email protected]')->middleware('guest');
});

Read more : Send Notification to Inactive User with Task Scheduling in Laravel using Custom Command

Step 3: Create FileUploadController

For creating controller , run below commands

php artisan make:controller Frontend\Auth\RegisterController

Step 4: Create blade template

Now we have to create uour html form to submit our data. So now create a file.

resources\authentication\register.blade.php

Step 5: Create a validation trait

Before submitting our form data , we have to validate our input form data. So now create a Trait like following path and paste the following code.

App\Validation\RegisterRequest.php

namespace App\Validation;

use Illuminate\Support\Facades\Validator;

Trait RegisterRequest 
{
    public function inputDataSanitization($data)
    {
        $validator = Validator::make($data, [
           'name' => 'required',
           'email' => 'required',
           'password' => 'required|min:6|confirmed',
           'photo' => 'required|image'
        ]);
        
        if($validator->fails()){

         return redirect()->back()->withErrors($validator)->withInput();

        }

        return $validator;
    }
}

Step 5: Create a photo upload trait

Now we will create a trait which is used for submitting file. This trait will help us to upload our file.

App\FileUpload\UserPhoto.php

namespace App\FileUpload;

use Illuminate\Support\Str;

Trait UserPhoto {

	public function UserFileUpload($file)
	{
		$file_name = uniqid('photo_',true).Str::random(10).'.'.$file->getClientOriginalExtension();

		if($file->isValid()){
			$file->storeAs('images',$file_name);
		}
	}
}

Here $filename contains the unique id "photo_" then a 10 digit random number and then finally file extension.

Step 6: Setup RegisterController

App\Http\Controllers\Frontend\Auth\RegisterController.php


namespace App\Http\Controllers\Frontend\Auth;

use App\FileUpload\UserPhoto;
use App\Http\Controllers\Controller;
use App\Validation\RegisterRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class RegisterController extends Controller
{   
	use UserPhoto,RegisterRequest;

    public function ShowRegisterForm()
    {
    	return view('authentication.register');
    }

    public function HandleRegister(Request $request)
    {
        $this->inputDataSanitization($request->all());

        $photo = $request->file('photo');
        
        $this->UserFileUpload($photo);

        $data = [
            'name' => trim($request->input('name')),
            'email' => strtolower($request->input('email')),
            'password' => bcrypt($request->input('password'))
        ];

        try {

            User::create($data);
            session()->flash('message', 'User created');
            session()->flash('type', 'success');
            return redirect()->route('frontend.login');
          
        } catch (\Exception $e) {

            session()->flash('message', $e->getMessage());
            session()->flash('type', 'danger');
            return redirect()->back();

        }
    }
}

Now just we have to one more thing. just open your config\filesystems.php and make changes like below.

'default' => env('FILESYSTEM_DRIVER', 'public'),

and here like below

'disks' => [

        'public' => [
            'root' => public_path('uploads'),
            'url' => env('APP_URL').'/uploads',
        ],
 ],

Now you are ready to upload your file. Hope you have enjoy this tutorial.

Codechief is a very fast growing community among programmers and have a reach of around 1 million+ readers globally. Contribution at Codechief is open for all those who have a passion to learn and help others by sharing their knowledge. If you think you have the zeal to learn, start contributing on Codechief contribute. you can also mail your article to [email protected] See your article appearing on the codechief main page and help other code.

We believe that everyone has the right to learn, so we allow both students and professionals to contribute on Codechief.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website