File Uploading

  • STEP

    In view

    1. Add enctype="multipart/form-data" to form tag

    2. method must be "POST"

    3. add input type="file" for file browsing, name attribute is 'input_field_name'

    
                      <form enctype="multipart/form-data" action="" method="post">
    
                            <input type="file" name="input_field_name">
    
                      </form>
                    

    Required class

    
                     use Illuminate\Support\Facades\File;
                    

    Read the uploaded file from the http request

    $request->file() is used for getting the uploaded file. Where $request is object of 'Request class'
    
                    $imageObj = $request->file('input_field_name');
                    

    Save the file in the server

    $imageObj->move() is used for storing the uploaded file in the server. Where $imageObj is object of 'Illuminate\Support\Facades\File class'
    
                    $imageObj->move(public_path('/uploads'), $file_name);  // first parameter is folder name, second parameter is file_name
                    

    Complete code

    
                    namespace App\Http\Controllers;
    
                    use Illuminate\Support\Facades\File;
    
    
                    class StudentController extends Controller
                    {
    
    
                        public function store(Request $request)
                        {
    
                                    if ($request->hasFile('input_field_name')) {
                                         $imageObj = $request->file('input_field_name');
                                         $file_name = $imageObj->getClientOriginalName()
                                         $imageObj->move(public_path('/uploads'), $file_name);
                                    }
                        }
    
                    }
    
    
    
    To get file extension
    
    $file_name = $imageObj->getClientOriginalExtension();
    

    To display the uploaded image in view blade

    
                    <img src="{{asset('public/uploads/'.$company['image'])}}">
                  
    $company is object of 'App\Models\Company model'