Skip to content

Instantly share code, notes, and snippets.

Last active March 3, 2021 02:21
What would you like to do?
Select2 and Laravel: Ajax Autocomplete
/* For more details see: */
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: --}}
<!doctype html>
<html lang="en">
<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="" rel="stylesheet">
<link href="" rel="stylesheet" />
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="tag_list">Tags:</label>
<select id="tag_list" name="tag_list[]" class="form-control" multiple></select>
<script src=""></script>
<script src=""></script>
<script src=""></script>
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
/* For more details see: */
Route::get('/tags', function() {
return view('tags');
Route::get('/tags/find', 'Select2Ajax\TagController@find');
Copy link


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