Reputation:
I am using ajax to retrieve data from my database into a select box. When i select a group, it should displays it contents respectively.
When i try to display the form, it says Undefined variable: packages
but i have return package in the view in my controller.
Is there anything i am missing out ?
PackageController
public function create()
{
$groups = Group::all();
$selectedGroup = $group->pluck('id')->toArray();
return view('group.detail',compact('selectedGroup','groups'));
}
public function getpackages($id)
{
$groups = Group::findOrFail($id);
$packages= $groups->packages;
return view('group.detail',compact('packages'));
return $id;
}
group.details.blade.php
<div class="input-group control-group after-add-more">
<div class="form-group">
<!-- <label for="select" class="col-lg-2 control-label">Select Item</label> -->
<div class="col-lg-10">
<select class="form-control" id="group" name="group[]" mulitple>
@foreach($groups as $group)
<option value="{!! $group->id !!}" @if(in_array($group->id, $selectedGroup)) selected="selected" @endif >
{!! $group->name!!}
</option>
@endforeach
</select>
</div>
</div>
<div class="form-group">
<!-- <label for="select" class="col-lg-2 control-label">Select Item</label> -->
<div class="col-lg-10">
<select class="form-control" id="remove_select" name="packages" mulitple>
@foreach($packages as $package)
<option value="{!! $package->id !!}" >
{!! $package->name!!}
</option>
@endforeach
</select>
</div>
</div>
<script>
$('#category').change(function(e)
{
e.preventDefault();
$y = $(this).val();
alert($y);
$.ajax
({
url: '{{ url('getpackages') }}/'+$y,
type: 'GET',
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
});
</script>
Upvotes: 1
Views: 694
Reputation: 6966
Both of your controller actions are using the same view, but neither of them are passing in all of the values that the view expects. When the create
controller action loads the view, it does not define the $packages
variable, which is why you are getting that notice.
You need to break your view into two separate views: One for the create
controller action and one for the getpackages
controller action.
I think the underlying issue here is that you are not treating your initial request and your ajax request separately.
Upvotes: 1