I have problem to returning json data and sort them in laravel, they just appear randomly.
What I did so far
I tried to return data by their
idfrom database and help of JavaScript like:result.sort(function(a,b) { return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0); });Result was random order (sort)I added
sortcolumn to my database and tried to get my data base on numbers I provided there (result was random order)I tried to add
->orderByRaw('set_specification.sort')in my function code and get orders by that (result was random order)
Logic
- I select a
set Setchild's will appear on blade bysortcolumn order which I provide numbers in it.
Code
controller
public function selectset($id){
$selectsets = DB::table('sets')
->where('sets.id', '=', $id)
->join('set_specification', 'sets.id', '=', 'set_specification.set_id')
->join('specifications', 'set_specification.spec_id', '=', 'specifications.id')
->orderByRaw('set_specification.sort')
->get();
return response()->json($selectsets);
}
JavaScript
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
result.sort(function(a,b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
console.log(result);
//rest of code..
}
Issues
Even when I return my data by help of ajax sort (as you see in my code) in console it returns correctly but in blade it appears as it wish!
in case image above won't work here it is again
Question
- How can I fix this sorting issue?
Update
I changed my ajax code to:
result.sort(function(a,b) {
return (a.sort > b.sort) ? 1 : ((b.sort > a.sort) ? -1 : 0);
});
and result is the same screenshot

sortcolumn in the database? I'm guessing it's not an integer. And if you're sorting byid, you need to specify the table, because you're joining multiple different tables.id, whereas the code suggests OP wants to ordered bysort, which appears to be astring, not anint.