Skip to content

Instantly share code, notes, and snippets.

@sahilkashyap64
Last active January 28, 2024 02:15
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sahilkashyap64/422e3a4672bf23d376f4e5b1ce7df7c7 to your computer and use it in GitHub Desktop.
Save sahilkashyap64/422e3a4672bf23d376f4e5b1ce7df7c7 to your computer and use it in GitHub Desktop.
Select2 with laravel pagination
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="page-header">
<h1>select2 with pagination</h1>
</div>
<select id='channel_id' style='width: 200px;'>
<option value='0'>- Search Channel -</option>
</select>
</div>
<script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<!--<![endif]-->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script >
(function() {
$("#channel_id").select2({
placeholder: 'Channel...',
// width: '350px',
allowClear: true,
ajax: {
url: '/dataforselect2',
dataType: 'json',
delay: 250,
data: function(params) {
return {
term: params.term || '',
page: params.page || 1
}
},
cache: true
}
});
})();
</script>
</body>
</html>
public function getdataforselect2(Request $request){
if ($request->ajax()) {
$term = trim($request->term);
$posts = DB::table('channels')->select('id','name as text')
->where('name', 'LIKE', '%' . $term. '%')
->orderBy('name', 'asc')->simplePaginate(10);
$morePages=true;
$pagination_obj= json_encode($posts);
if (empty($posts->nextPageUrl())){
$morePages=false;
}
$results = array(
"results" => $posts->items(),
"pagination" => array(
"more" => $morePages
)
);
return \Response::json($results);
}
}
Route::get('/tags', function() {
return view('Somefolder.index');
});
Route::get('dataforselect2', 'SomeController@getdataforselect2')->name('dataforselect2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment