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
in your controller query to get the sum of all allocations for a legislator
Or to get the latest 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
your controller
I hope this helps
if possible kindly share the code repo