Last active
March 3, 2021 02:21
-
-
Save FilipQL/f7b2e714f48f85bf9bca0e3a7e259a70 to your computer and use it in GitHub Desktop.
Select2 and Laravel: Ajax Autocomplete
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 | |
/* 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); | |
} | |
} |
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 | |
/* 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'); |
@Gabriel-Caruso
You can simply protect the url:
url: '/tags/find',
In this case, on TagController.php
you can add:
public function __construct()
{
// Only Authenticated Users can access
$this->middleware('auth');
}
Or you can do this from the Routes
@Gabriel-Caruso see this link
No logra mostrar nada mi select en el buscador cuando tengo datos que mostrar
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Gabriel-Caruso Since it's a GET request, you don't need to append the CSRF token. Am I right?