I have a myitems($filter) method in a ItemsController that loads the myitems.blade view.
The view has list of items as label and text box to get number of items ($items is passed from myitems method to myitems view and there is a model form binding on items model as well)
I have a select box that has options 1. All, 2. Expired and 3.New
When I change the selection I want to have get new $items from the controller and recreate the form with new items list.
I am using using jquery to alert that the selection is changed. but I am not able to figure out how will I be able to call myitems($filter) from ajax and redirect to create the items.blade page.
Route
//Note the ? in parameter, it says parameter is optional
Route::get('/myitems/{filter?}',
['as' => 'myitems.list', 'uses' => 'ItemController@myitems']
);
Controller
...
public function myitems(Request $request, $filter = null)
{
if (empty($filter)) $filter=1;
$items = Item::where('item_type', $filter)->get();
// if ajax call just return the partial that displays the list
if ($request->ajax()) {
return view('_itemlist', compact('items'));
}
// passed as options to input select
$filters= [
'All' => '0',
'New' => '1',
'Expired' => '2'
];
return view('itempagewith_defaultitemlist', compact('items','filters'));
}
...
View
view itempagewith_defaultitemlist.blade.php
<div class="container">
{!! Form::model($myitems, ['route' => 'myitems.list', 'class'=>'form-horizontal', 'files' => true]) !!}
<div id="filterselectbox">
<div class="form-group">
{!!Form::label('filterselectbox','*Filter:',['class'=>'control-label']) !!}
{!!Form::select('filterselectbox', $filters, null, ['class'=>'form-control ']) !!}
</div>
</div>
{!! Form::close() !!}
<div id="item-container">
@include('_itemlist')
</div>
<script>
$('#filterselectbox').change(function() {
var id = $('#filterselectbox').val();
var ajaxurl = '{{route('myitems', ':id')}}';
ajaxurl = ajaxurl.replace(':id', id);
$.ajax({
url: ajaxurl,
type: "GET",
success: function(data){
$data = $(data); // the HTML content that controller has produced
$('#item-container').hide().html($data).fadeIn();
}
});
});
</script>
</div>
partial view _itemlist.blade.php
<ul>
@foreach ($items as $item)
<li>{{ $item->name }}</li>
@endforeach
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With