Created
July 26, 2018 09:22
-
-
Save Ahed91/7d3e21e2ba22e8fdc6ff7d02b0fd2e04 to your computer and use it in GitHub Desktop.
select2 with laravel controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
class CityController extends BaseController | |
{ | |
public function getRegions() | |
{ | |
$s = request()->get('q', ''); | |
$data = Region::where('name_ar', 'like', \DB::raw('"%' . $s . '%"'))->paginate(); | |
return $data->toJson(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/i18n/ar.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function () { | |
$('select[name="region"]').select2({ | |
language: "ar", | |
dir: "rtl", | |
ajax: { | |
url: "{{ route('admin.ajax.regions') }}", | |
dataType: 'json', | |
delay: 250, | |
data: function (params) { | |
return { | |
q: params.term, // search term | |
page: params.page | |
}; | |
}, | |
processResults: function (data, params) { | |
// parse the results into the format expected by Select2 | |
// since we are using custom formatting functions we do not need to | |
// alter the remote JSON data, except to indicate that infinite | |
// scrolling can be used | |
console.log(data); | |
params.page = params.page || 1; | |
return { | |
results: $.map(data.data, function (item) { | |
return { | |
text: item.name, | |
slug: item.slug, | |
id: item.id | |
} | |
}), | |
pagination: { | |
more: (params.page * 30) < data.total_count | |
} | |
}; | |
}, | |
cache: true | |
}, | |
escapeMarkup: function (markup) { | |
return markup; | |
}, // let our custom formatter work | |
}); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment