Laravel 500 Internal Server Error when submitting form

Viewed 60

I am getting this error when submitting a form with ajax, I have tried without ajax and it throws the same result. Laravel is making no logs and I have tried to clear cache and update the app key but nothing happens.

Error Image : Internal Error Image

Here's my controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Products;
use Illuminate\Support\Facades\File;


class ProductController extends Controller
{


    //Search Products
    public function search(Request $request)
    {
          $products = Products::where('name','like', '%'.$request->search.'%')                
           ->orWhere('id','like', '%'.$request->search.'%')->get();

        $output = "";
        foreach($products as $products)
        {
            $output.=
            '<tr class="border-bottom border-dark p-3">
                <td>'.$products->name.'</td>
                <td>'.$products->s_description.'</td>
                <td>'.$products->l_description.'</td>
                <td class="align-center p-5"><img class="img-fluid" src='.asset('images')."/".$products->image_src.'></td>
                <td>'.$products->category.'</td>
                <td>'.$products->quantity.'</td>
                <td>'.$products->price.'</td>
                <td>'.'
                    <form action='.route('delete_product', $products->id).' method="POST" id="deleteBtn">
                    z
                    <input type="hidden" name="_method" value="delete">
                    <button class="btn btn-danger" type="submit">'.'Delete</button>
                    </form>
                    '.'
                </td>
               
             </tr>
            ';
        }

        return response($output);
    }



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function viewProducts()
    {
        $p_details = Products::all();
        return view('admin.products.view_products',compact('p_details'));                              
    }

    
    public function productVerify(Request $request)
    {

         $request->validate
            (
                [
                    'name' => 'required',
                    's_description' => 'required',
                    'l_description' => 'required',
                    'image_src' => 'required|mimes:jpg,png,jpeg',
                    'category' => 'required',
                    'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',                  
                    'price'  => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',                        
                ]
            );
           
            // return validation rules;
            $val = $this->productVerify($request);

            if ($val->fails())
            {                
                    return response()->json(['errors' => $val->errors()->all()]);                  
                             
            }
            else
            {
                return redirect()->to('view_products')
                ->with('success','Product added successfully');
               
            }
            
            
            
            
            
    }


    //Uploading Images 
    public function validImg(Request $request)
    {       
       
           
            if ($request->hasFile('image_src')) 
            {
                $filename = $request->file('image_src');
                $filename->getClientOriginalName();
                $filename = time().$filename->getClientOriginalName();
                $destinationPath = base_path("/public/images");
                $request->file('image_src')->move($destinationPath,$filename);
                $data['image_src'] = $filename;
            }
            return $data['image_src'];

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.products.add_products');
    }

    //Creating and Adding Products
    public function createProduct(Request $request)
    {  
              

                //Product Validation
                $this->productVerify($request);
            
                
                $data = $request->all();
                $image_src = $this->validImg($request);
                
                Products::create
                ([
                    'name' => $data['name'],
                    's_description' => $data['s_description'],
                    'l_description' => $data['l_description'],
                    'category' => $data['category'],
                    'quantity' => $data['quantity'],
                    'price' => $data['price'],
                    'image_src' => $image_src

                ]);
        

        

       
}

    

     /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product_edit = Products::findOrFail($id);
        return view('admin.products.edit_products',                               
        compact('product_edit'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //Product Validation
        $validatedData = $this->productValidation($request);
        
        $this->validImg($request);
    
        Products::whereId($id)->update($validatedData);

        return redirect('view_products')->with('success', 'Product details 
        successfully updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $products = Products::findOrFail($id);
        
        $destinationPath = base_path("/public/images").'/'.$products-             >image_src;
        if(File::exists($destinationPath))
        {

            File::delete($destinationPath); 
            //for deleting only file try this
            
            $products->delete(); //for deleting record and file try both
    
        }

        // $products->delete();

        return redirect('view_products')->with('error', 'Product successfully deleted');
    }
}

Here's my add_products.blade.php:

@extends('admin.home.master')
@section('content')

    
      <div class="main-content">
        <div class="section-body">
          <div class="row ">

            <div class="col-lg-2"></div>

              <div class="col-8 col-md-8 col-lg-8">
               <form id="addForm" enctype="multipart/form-data" method="POST">
                @csrf
                
                <div class="card">
                  <div class="card-header">
                    <h4>Add Product</h4>
                  </div>
                  <div class="card-body">

                    <div class="form-group">
                      <label>Product Name</label>
                      <input name="name" type="text" class="form-control">
                      
                    </div>
                    <div class="form-group">
                      <label>Short Description(approx 1 line)</label>
                      <div class="input-group">
                        <div class="input-group-prepend">
                        </div>
                        <input name="s_description" type="text" class="form-control phone-number">
                      </div>
                      <div class="s_description">
                       
                      </div>
                    </div>
                    <div class="form-group">
                      <label>Long Description</label>
                      <div class="input-group">
                        <div class="input-group-prepend">
                        </div>
                        <input name="l_description" type="text" class="form-control pwstrength" data-indicator="pwindicator">
                        
                      </div>
                      
                      <div id="pwindicator" class="pwindicator">
                        <div class="bar"></div>
                        <div class="label"></div>
                      </div>
                    </div>
  
                    <div class="form-group">
                      <label>Category</label>
                      <br>
                      <div class="input-group mx-4 my-2">
                        <input  name="category" value="clothing" class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
                        <label class="form-check-label" for="flexRadioDefault1">
                          Clothing
                        </label>
                      </div>
                      <div class="input-group mx-4 my-2">
                        <input  name="category" value="mobiles" class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
                        <label class="form-check-label" for="flexRadioDefault1">
                          Mobiles
                        </label>
                      </div>
                      <div class="input-group mx-4 my-2">
                        <input name="category" value="computers" class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
                        <label class="form-check-label" for="flexRadioDefault1">
                          Computers
                        </label>
                      </div>
                      
                    <div class="form-group">
                      <label>Product Image</label><br>
                      <span class="text-success">* Image format should be JPG, JPEG, or PNG</span><br>
                      <div class="input-group">
                      
                        <input id="image_src" name="image_src" type="file" class="form-control currency">
                        
                      </div>
                      
                    </div>
                   
                    <div class="form-group">
                      <label>Quantity</label><br>
                      <span class="text-success">* Value should be greater than 0</span><br>
                      <input name="quantity" type="number" class="form-control invoice-input" min="1" oninput="validity.valid||(value='');">
                      
                    </div>  
                    <div class="form-group">
                      <label>Price</label><br>
                      <span class="text-success">* Value should be greater than 0</span><br>
                      <input name="price" type="number" class="form-control invoice-input" min="1" oninput="validity.valid||(value='');">
                      
                   
                    <button type="submit" id="submit" class="btn btn-primary mt-2">Submit</button>
                  </div>

                  <div id="error">
                    <!-- Display errors here -->
                  </div>

                </div>

               </form>
     
              </div>
            
            
            <div class="col-lg-2"></div>

          </div>
        </div>
      </div>
   
      <script src="{{asset('theme/assets/ajax/add_product.ajax.js')}}"></script>



@endsection

Here's my ajax file:

 $(document).ready(function()
 {
       $("#addForm").submit(function(event)
       {
           
           // Store all data from form as object;
           var formData = new FormData(this);

           jQuery.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
            });
        
           // AJAX implementation error:function() return errors without page reload.
           $.ajax(
           {
             url: '/save_product',
             type: "POST",
             processData:false,  
             contentType:false,
             cache:false,
             dataType: 'json',
             data:formData,
  
             error:function(xhr, status, error) 
                 {
                    // Errors from the XML Http Request JSON Response
                     responseER = xhr.responseJSON.errors;
                    //  console.log(responseER);
                     $("#error").html(" ");
                     // For Each loop for printing errors from the response 
                     $.each(responseER, function (key, item) 
                     {
                        
                        $("#error").append("<li class='text-danger'>"+item+"</li>")
                       // Hide Errors after 15 seconds with a fadeout animation
                        $("#error").show().delay(15000).fadeOut();
                       
                       
                        
                     });

                    
                    
                     
                     
                }
                
                 
           });  
           // Stop form from submitting normally
           event.preventDefault();
         
       });
       
       
   });

0 Answers
Related