rafitio rafitio - 1 month ago 22
Javascript Question

how to filter table using dropdown on laravel

i want to filter my table using dropdown on laravel, it has been works, but when i want to create a new record at the create form, the create form just show the data of the getid function, not create form view.

here my code

<form method="GET">
<div id="sample-table-3">
<label>Display as Category</label>
<select name="category_id" id="category_id">
<option value="0">Show All</option>
@foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->category }}</option>
@endforeach
</select>
</div>
</form>


here the javascript

<script type="text/javascript">
$(document).ready(function(){
$('#category_id').on('change', function(e){
var id_category = e.target.value;
$.get('{{ url('news')}}/'+id_category, function(data){
console.log(id_category);
console.log(data);
$('#news_data').empty();
$.each(data, function(index, element){
$('#news_data').append("<tr><td>"+element.title+"</td><td>"+element.file+"</td>"+
"<td>"+element.content+"</td><td>"+element.like+"</td><td>"+element.view+"</td><td>"+find('.action')+"</td></tr>");
});
});
});
});
</script>


and this my controller

public function index(Request $request)
{
$news = News::paginate(10);
$categories = Category::all();


return view('news.news')
->with(compact('news'))
->with(compact('categories'));
}

public function create()
{
$news = News::all();

/* Get Category */
$categories = Category::all();

//dd($categories);
return view('news.create')
->with(compact('news'))
->with(compact('categories'));
}

public function getid($id_category){
$categories = Category::all();

if($id_category==0){
$news = News::all();
}else{
$news = News::where('category_id','=',$id_category)->get();
}
return $news;
}


and this my route

Route::get('/news/{id_category}', 'NewsController@getid');


Route::group(['middleware' => 'web'], function () {

Route::resource('news', 'NewsController', ['except' => ['getid']]);
Route::resource('category', 'CategoryController');


});

Answer

Your route

Route::get('/news/{id_category}', 'NewsController@getid');

is probably clashing with the show route of NewsController.

Change it to something like so

Route::get('/news/getid/{id_category}', 'NewsController@getid');