anyone ):
Oct 15, 2019
5
Level 1
how to store Polymorphic related model data
I want to make a dependent dropdown list, there are 2 Models that should list their data and save them in the Account table.i made their relation in model correctly. in the first select option, I put "person" and "employee" static. and made a condition for getting their data. I've come so far, it works somehow, but I wonder how to store the data in the controller. any assistance would be really appreciated.
Account Model
class Account extends Model
{
protected $guarded = [];
public function accountable()
{
return $this->morphTo();
}
}
Employee Model
class Employee extends Model
{
protected $guarded = [];
public function account()
{
return $this->morphOne(Account::class, 'accountable');
}
}
Person Model
class Person extends Model
{
protected $guarded = [];
public function accounts()
{
return $this->morphMany(Account::class, 'accountable');
}
}
This is The Form:
<div class="form-group">
<label class="col-md-3 control-label">Accountable</label>
<div class="col-md-5">
<select class="form-control select2me" name="accountable_type">
<option value=""></option>
<option value="person">Person</option>
<option value="employee">Employee</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Accountable_Type</label>
<div class="col-md-5">
<select name="accountable_id" class="form-control select2me">
{{-- <option value=""></option> --}}
</select>
</div>
</div>
This is AJAX method :
<script>
$(document).ready(function() {
$('select[name="accountable_type"]').on('change', function() {
var person_id = $(this).val();
if(person_id == 'person') {
$.ajax({
url: "{{URL('get_person')}}",
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="accountable_id"]').empty();
$.each(data, function(key, value) {
$('select[name="accountable_id"]').append('<option value="'+ key +'">'+
value.name +'</option>');
});
}
});
}else{
$('select[name="accountable_id"]').empty();
}
});
$('select[name="accountable_type"]').on('change', function() {
var employee_id = $(this).val();
if(employee_id == 'employee') {
$.ajax({
url: "{{URL('get_employee')}}",
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="accountable_id"]').empty();
$.each(data, function(key, value) {
$('select[name="accountable_id"]').append('<option value="'+ key +'">'+
value.name +'</option>');
});
}
});
}else{
$('select[name="accountable_id"]').empty();
}
});
});
</script>
Please or to participate in this conversation.