skip to Main Content

I am new to laravel. I try to automatically display the allocation values on the input field when the particular name of legislator is selected but, I only get an allocation:null. Please help me.

My create allocation table

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up()
    {

        // Drop the table if it exists
        Schema::dropIfExists('allocations');


        Schema::create('allocations', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('name_of_legislator_id');
            $table->bigInteger('allocation');
            $table->foreign('name_of_legislator_id')->references('id')->on('name_of_legislators');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('allocations');
    }
};

My allocation model

class Allocation extends Model
{
    use HasFactory;

    protected $table = 'allocations';

    protected $fillable = [
        'name_of_legislator_id',
        'allocation'
    ];

    public function nameOfLegislator()
    {
        return $this->belongsTo(NameOfLegislator::class, 'name_of_legislator_id', 'id');
    }
}

**my controller **

  public function getAllocations(Request $request)
  {
    $legislatorID = $request->name_of_legislator_id;

    if ($request->ajax()) {
      $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->value('allocation');
      return response()->json(['allocation' => $allocation]);
    }
  }

My jquery and html

            $(document).on("change", ".legislator", function(e) {
                e.preventDefault();

                let legislatorID = $(this).val();

                $.ajax({
                    type: "POST",
                    url: "{{ route('targets.get-allocations') }}",
                    data: {
                        name_of_legislator_id: legislatorID
                    },
                    success: function(response) {
                        let allocationInput = $(".allocation");

                        if (response && response.allocation !== null) {
                            allocationInput.val(response.allocation);
                        } else {
                            allocationInput.val('');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.log(xhr.responseText);
                    }
                });
            });
     <td>
    <input type="number" name="allocation" class="form-control allocation"                placeholder="Allocation" required min="0" readonly>
    </td>

What I want is when the particular of name of legislator is selected on the dropdown, the allocation values that is assigned to them will automatically display on the input field.

2

Answers


  1. Chosen as BEST ANSWER
    I update my controller and jquery and still get a allocation:null and didn't get any error on my console
    
    **my controller** 
    public function getAllocations(Request $request)
      {
        $legislatorID = $request->name_of_legislator_id;
    
        if ($request->ajax()) {
          Log::info('Request received to fetch allocation for legislator ID: ' . $legislatorID);
    
          $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->value('allocation');
    
          if ($allocation !== null) {
            Log::info('Allocation found: ' . $allocation);
          } else {
            Log::warning('No allocation found for legislator ID: ' . $legislatorID);
          }
    
          return response()->json(['allocation' => $allocation]);
        }
      }
    
    **my js** 
                $(document).ready(function() {
                    $(document).on("change", ".legislator", function(e) {
                        e.preventDefault();
                        let legislatorID = $(this).val();
    
                        $.ajax({
                            type: "POST",
                            url: "{{ route('targets.get-allocations') }}",
                            data: {
                                _token: "{{ csrf_token() }}",
                                name_of_legislator_id: legislatorID
                            },
                            success: function(response) {
                                let allocationInput = $(".allocation");
                                if (response && response.allocation !== null) {
                                    allocationInput.val(response.allocation);
                                } else {
                                    allocationInput.val('');
                                }
                            },
                            error: function(xhr, status, error) {
                                console.log(xhr.responseText, error);
                            }
                        });
                    });
                });
    

  2. in your controller query to get the sum of all allocations for a legislator

    $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->sum('allocation');
    

    Or to get the latest allocation

    $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->latest()->value('allocation');
    

    but the way i noticed you have mentioned that you are getting allocation:null this could be due to some comman reasons

    kindly check the database record for example
    in your allocations table and that the name_of_legislator_id values correctly correspond to the id values in your name_of_legislators table. If there are no matching records, the query will return null.
    (this could be one reason)

    second kindly look for CSRF token in your jquery Ajax request
    https://laravel.com/docs/10.x/csrf

    <script>
    $(document).ready(function() {
        $(document).on("change", ".legislator", function(e) {
            e.preventDefault();
            let legislatorID = $(this).val();
    
            $.ajax({
                type: "POST",
                url: "{{ route('targets.get-allocations') }}",
                data: {
                    _token: "{{ csrf_token() }}", // Include CSRF token for Laravel
                    name_of_legislator_id: legislatorID
                },
                success: function(response) {
                    let allocationInput = $(".allocation");
                    if (response && response.allocation !== null) {
                        allocationInput.val(response.allocation);
                    } else {
                        allocationInput.val('');
                    }
                },
                error: function(xhr, status, error) {
                    console.log(xhr.responseText);
                }
            });
        });
    });
    </script>
    

    your controller

    public function getAllocations(Request $request) {
        if ($request->ajax()) {
            $legislatorID = $request->name_of_legislator_id;
            $allocation = Allocation::where('name_of_legislator_id', $legislatorID)->value('allocation');
            return response()->json(['allocation' => $allocation]);
        }
    }
    

    I hope this helps

    if possible kindly share the code repo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search