Skip to content

Instantly share code, notes, and snippets.

@FilipQL
Last active March 3, 2021 02:21
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save FilipQL/f7b2e714f48f85bf9bca0e3a7e259a70 to your computer and use it in GitHub Desktop.
Select2 and Laravel: Ajax Autocomplete
<?php
/* For more details see: http://laraget.com/blog/select2-and-laravel-ajax-autocomplete */
namespace App\Http\Controllers\Select2Ajax;
use App\Tag;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class TagController extends Controller
{
/**
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function find(Request $request)
{
$term = trim($request->q);
if (empty($term)) {
return \Response::json([]);
}
$tags = Tag::search($term)->limit(5)->get();
$formatted_tags = [];
foreach ($tags as $tag) {
$formatted_tags[] = ['id' => $tag->id, 'text' => $tag->name];
}
return \Response::json($formatted_tags);
}
}
{{-- For more details see: http://laraget.com/blog/select2-and-laravel-ajax-autocomplete --}}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<title>Select2 Ajax Example</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<form>
<div class="form-group">
<label for="tag_list">Tags:</label>
<select id="tag_list" name="tag_list[]" class="form-control" multiple></select>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$('#tag_list').select2({
placeholder: "Choose tags...",
minimumInputLength: 2,
ajax: {
url: '/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
</body>
</html>
<?php
/* For more details see: http://laraget.com/blog/select2-and-laravel-ajax-autocomplete */
Route::get('/tags', function() {
return view('tags');
});
Route::get('/tags/find', 'Select2Ajax\TagController@find');
@MirianSaucedo
Copy link

No logra mostrar nada mi select en el buscador cuando tengo datos que mostrar

@MirianSaucedo
Copy link

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment