In this section, we will see how to use Select2 for multiple selections in Laravel 8. The question is, when and why should we use Select2? The answer is simple: when we need to create tag fields, dynamic searches, or a Twitter-like #(tag) system. For this tutorial, we will use the Select2 CDN, or you can install it using the npm package.
Create Laravel Project
Run below command to create laravel project.
composer create-project laravel/laravel laravel-intervention
Now, you need to connect the Laravel app to the database. Open the .env configuration file and add the database credentials as suggested below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Create Post Model
php artisan make:model Post -m
Add values in the migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->longText('tags');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title', 'description', 'tags'
];
}
Create post route in web.php
<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('posts', PostController::class);
Create Post Controller
php artisan make:controller PostController -r
app/Http/Controllers/PostController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('select-2');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required',
'description' => 'required',
'tags' => 'required',
]);
// $data['tags'] = implode(",", $request->tags);
$data['tags'] = json_encode($request->tags);
$post = Post::create($data);
return redirect()->route('posts.index')->with('success', 'Post created successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Create Post blade file
app/resources/views/select-2.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to use select2 for multiple select in laravel</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{{-- selec2 cdn --}}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<div class="container mt-5">
<form action="{{ route("posts.store") }}" method="POST">
@csrf
<div class="mb-3">
<label class="form-label">Title</label>
<input type="text" class="form-control" name="title" placeholder="title">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Description</label>
<textarea class="form-control" name="description" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<div class="form-group mb-3">
<label for="select2Multiple">Multiple Tags</label>
<select class="select2-multiple form-control" name="tags[]" multiple="multiple"
id="select2Multiple">
<option value="tag1">tag1</option>
<option value="tag2">tag2</option>
<option value="tag3">tag3</option>
</select>
</div>
<button type="submit" class="btn btn-primary">submit</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
// Select2 Multiple
$('.select2-multiple').select2({
placeholder: "Select",
allowClear: true
});
});
</script>
</body>
</html>