File upload using laravel – ajax

File uploads is one of the most important functions on the internet, and we have bigger files nowadays, which means it’s not enough to have simple input fields – we need AJAX and processing file upload “in the background”. Here I will show you a simple example:

view:

<form id="example-form" method="post" enctype="multipart/form-data">
    {!! csrf_field() !!}
    <div class="row">
        <div class="col m12">
            <div class="row">
                <div class="input-field col m12 s12">
                    <input id="name" name="name" type="text" placeholder="Full Name" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="email" name="email" type="email" placeholder="Email" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="phone_number" name="phone_number" type="tel" placeholder="Phone Number" class="required validate">
                </div>                                                        
                <div class="input-field col m6 s12">
                    <input id="address" name="address_city_village" type="text" placeholder="Address City Village">
                </div>
                <div class="input-field col m6 s12">
                    <input id="state" name="address_state" type="text" placeholder="State">
                </div>                                                        
                <div class="input-field col s12">
                    <input id="password" name="password" type="password" placeholder="Password" class="required validate">
                </div>
                <div class="input-field col s12">
                    <input id="confirm" name="confirm" type="password" placeholder="Confirm Password" class="required validate">
                </div>
                <div class="file-field input-field col s12">
                    <div class="btn teal lighten-1">
                        <span>Image</span>
                        <input type="file" name="image">
                    </div>
                    <div class="file-path-wrapper">
                        <input class="file-path validate" type="text" >
                    </div>
                </div>                                                        
            </div>
        </div>
    </div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="waves-effect waves-green btn blue">Submit</button>
</div>
</form>
Method-1

<script>

$('form').submit(function(event) {
    event.preventDefault();
    var formData = new FormData($(this)[0]);
    $.ajax({
        url: '{{ url('/agents') }}',
        type: 'POST',              
        data: formData,
        success: function(result)
        {
            location.reload();
        },
        error: function(data)
        {
            console.log(data);
        }
    });

}); </script>
Method-2

<script>

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'route_url',
                dataType    : 'text',  // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);  // display response from the PHP script, if any
                }
         });
    });

</script>
Controller

public function store(Request $request)
{
    if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
       return $this->respondBadRequest('Phone Number Exists');
    }
    else 
    {
        $user=User::create($request->all());

        if($request->hasFile('image')) {
           $file = $request->file('image');

           //you also need to keep file extension as well
           $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

           //using the array instead of object
           $image['filePath'] = $name;
           $file->move(public_path().'/uploads/', $name);
           $user->image= public_path().'/uploads/'. $name;
           $user->save();
        }
        return redirect('agents')->with('Success', 'Agent Added');
    }
}

 

 

 

Leave a Reply