DEV Community

loading...

Adding Select2 to Laravel (The Laravel-Mix Way)

Dendi Handian
I am that backend programmer who doesn't return 200 OK for errors and doesn't write only POST method for all endpoints.
Updated on ・2 min read

I will keep adding more js package that I use or you might use when you're using jQuery in the stack, this time is Select2. Select2 gives you additional input on the <select> element to filter the options. Now let's find out how to add it to your laravel app with Laravel-Mix.

Prerequisites to code along

Have your own laravel app and you ever use sass/scss and javascript with laravel (using laravel-mix). Not to mention, you already have jQuery installed in your app.

Installing Select2

Open your terminal, go to your laravel app, and here is the command to install:

npm install select2 --save-dev
Enter fullscreen mode Exit fullscreen mode

Applying Select2 JS

In your entrypoint or bootstrapped js file, you may have a similar code like this:

window._ = require('lodash');

try {

    window.$ = window.jQuery = require('jquery');

} catch (error) {
    console.log(error);
}
Enter fullscreen mode Exit fullscreen mode

now we just add the select2 below the jquery requirement and apply the select2 globally to any <select> element in your web (You may want to change it to your preference):

window._ = require('lodash');

try {

    window.$ = window.jQuery = require('jquery');

    require('select2');
    $('select').select2();

} catch (error) {
    console.log(error);
}
Enter fullscreen mode Exit fullscreen mode

Applying Select2 CSS

At this point, your select2 won't work unless you apply the style as well. In your sass/scss entrypoint file, add this line:

...

@import "~select2/dist/css/select2.css";

...
Enter fullscreen mode Exit fullscreen mode

Build!

npm run development
Enter fullscreen mode Exit fullscreen mode

or

npm run production
Enter fullscreen mode Exit fullscreen mode

Test it!

Let's put this simple select html element from w3schools in your web:

<label for="cars">Choose a car:</label>

<select name="cars" id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
Enter fullscreen mode Exit fullscreen mode

And see it whether it applies or not by yourself, let me know if it doesn't 👻.


version used:

node v14.16.0
npm 6.14.11
laravel-mix 6.0

Enter fullscreen mode Exit fullscreen mode

Discussion (0)