Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ollie_123's avatar

Ajax file upload form - call to member function extension null

Evening All

I'm trying to post a form to the database & to upload a file at the same time.

I'm getting an error 500 call to member function extension() on Null which indicates its not getting the file extension. Please can someone tell me the best way to correct this.

Controller

public function store(Request $request)
        { 
            $request->validate([
                'sw_manual' => 'required',
                'sw_os' => 'required',
                'sw_link' => 'required|mimes:png,jpg|max:2048',

                $softwareEnq = time().'.'.$request->file->extension(),
                $request->file->move(public_path('admin/software'), $softwareEnq),
                
            ]);
                $softwareEnq = \App\TuningSoftware::updateOrCreate(
                    
                
            ['id' => $request->software_id],
            [  
                'sw_link' => $request->sw_link->store('admin/software'),
                'sw_type' => $request->sw_type, 
                'sw_manual' => $request->sw_manual, 
                'sw_os' => $request->sw_os, 
                'status' => $request->status
            ]
        );
            return Response::json($softwareEnq);
        }
        
        /**
         * Show the form for editing the specified resource.
         *
         * @param  \App\User  $User
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {   
            $where = array('id' => $id);
            $softwareEnq  = \App\TuningSoftware::where($where)->first();

            return Response::json($softwareEnq);
        }

HTML Snippet

<div class="row">
                            <div class="col-sm-12">
                                <label>Manual</label>
                                <input type="text" class="form-control" id="sw_manual" name="sw_manual">
                            </div><!-- end col -->
                        </div><!-- end row -->

                        <div class="padb-20"></div>
                    <div class="row">
                        <div class="col-sm-12">
                            <label>Upload File</label>
                            <input type="file" name="sw_link" id="sw_link">
                        </div>
                    </div><!-- end row -->

JS

<script>
  $(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    /*  When user click add user button */
    $('#create-new-post').click(function () {
        $('#btn-save').val("create-user");
        $('#userForm').trigger("reset");
        $('#softwareModal').html("Add New Software");
        $('#ajax-crud-modal').modal('show');
    });
 
   /* When click edit user */
    $('body').on('click', '#edit-user', function () {
      var softwareEnq_id = $(this).data('id');
      $.get('softwareEnq/' + softwareEnq_id +'/edit', function (data) {
         $('#softwareModal').html("Edit Enquiry");
          $('#btn-save').val("edit-user");
          $('#ajax-crud-modal').modal('show');
          $('#software_id').val(data.id);
          $('#sw_type').val(data.sw_type);
          $('#sw_os').val(data.sw_os);
          $('#sw_link').val(data.sw_link);
          $('#sw_manual').val(data.sw_manual);
          $('#status').val(data.status);
      })
   });
   //delete user
    $('body').on('click', '.delete-user', function () 
    {
        var softwareEnq_id = $(this).data("id");
        if(confirm("Are You sure want to delete !")) 
        {$.ajax({
                type: "DELETE",
                url: "{{ url('softwareEnq')}}"+'/'+softwareEnq_id,
                success: function (data) 
                {
                    $("#softwareEnq_id" + softwareEnq_id).remove();
                },
                error: function (data) 
                {
                    console.log('Error:', data);
                }
            });
        }
    });   
  });
 
 if ($("#userForm").length > 0) {
      $("#userForm").validate({
 
     submitHandler: function(form) {
 
      var actionType = $('#btn-save').val();
      $('#btn-save').html('Sending..');
      
      $.ajax({
          url: "{{ url('softwareEnq') }}",
          type: "POST",
          data: $('#userForm').serialize(),
          dataType: 'json',
          success: function( data ) 
            {
                $('#send_form').html('Submit');
                $('#position-1-success-changelog').show(function() 
                {
                    
                var notice = new PNotify({
                    title: 'Success',
                    text: 'Software Status Updated.',
                    type: 'success',
                    icon: 'fa-check-circle',
                    addclass: 'stack-bottomleft'
                }); //end function
            }); //end response  

            // console.log('Success:', data);
 
              $('#updateTable').trigger("reset");
              $('#ajax-crud-modal').modal('hide');
              $('#btn-save').html('Save Changes');
            //   console.log('Info:', data);
                setTimeout( 
                    function() {
                        window.location.reload(true);
                    }, 800);
          },
          error: function (data) {
              console.log('Error:', data); // remove this for production
              $('#btn-save').html('Save Changes');
          }
      });
    }
  })
}
</script>

Thank you in a advance.

0 likes
5 replies
Tray2's avatar

This looks very wrong to me

      $request->validate([
                'sw_manual' => 'required',
                'sw_os' => 'required',
                'sw_link' => 'required|mimes:png,jpg|max:2048',

                $softwareEnq = time().'.'.$request->file->extension(),
                $request->file->move(public_path('admin/software'), $softwareEnq),
                
            ]);

These two line does not seem to belong in the validation

   $softwareEnq = time().'.'.$request->file->extension(),
                $request->file->move(public_path('admin/software'), $softwareEnq),

However that is beside the point.

Check this link on how to handle uploads https://laravel.com/docs/6.x/requests#files

ollie_123's avatar

Whilst i appreciate that in my code i had something in the incorrect place, (an error on my part), i have already read the laravel docs and im struggling to see how i do this in Ajax. It doesn't seem to be obtaining the file and storing it.

Updated Controller...

public function store(Request $request)
        { 
            
            $path = $request->file('sw_link')->store('public/uploads');

                $softwareEnq = \App\TuningSoftware::updateOrCreate(
                    
                
            ['id' => $request->software_id],
            [  
                'sw_link' => $request->sw_link->store('admin/software'),
                'sw_type' => $request->sw_type, 
                'sw_manual' => $request->sw_manual, 
                'sw_os' => $request->sw_os, 
                'status' => $request->status
            ]
        );
            return Response::json($softwareEnq);
        }
Tray2's avatar

Do a dd($request); and share what it contains. There you should be able to see if there is a file or not.

ollie_123's avatar

Hey Tray

I got the following:-

local.ERROR: Call to a member function store() on null

Please or to participate in this conversation.