Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Guide on how to Slug an HTML Field in Laravel

Slug an HTML Field in Laravel

Follow this guide to learn how to easily slug an HTML field in Laravel. You can also use this guide for other HTML projects with some tweaking.



The following is an example where when text is entered into the title field, it will dynamically slug it in the slug field.

<script src="{{ asset('js/app.js') }}"></script>

<label for="title">Title</label>
<input type="text" class="form-control" name="title" id="title" value="{{ old('title') }}" oninput="slugifyField('title', 'slug')">

<label for="slug">Slug (URL) - Must be a single string (eg: "my-new-post" OR "mynewpost")</label>
<input type='text' class='form-control' name='slug' id="slug" value="{{ old('slug') }}">


The following must be placed inside a <script> tag on the page you want to slug a field.

// slugifyField slugs the title field to create a url slug
function slugifyField(textfield, slugField) {
    let textFieldValue = document.getElementById(textfield).value
    let slug = slugify(textFieldValue)
    document.getElementById(slugField).value = slug

Import Slugify

You'll need to import the node module that actually slugifies text. Add the following to your resources/js/app.js file in your Laravel project. If not using laravel, add this to whatever js file loads with Webpack.

window.slugify = require('@sindresorhus/slugify')

Find install and usage instructions here. You'll need to install slugify into your node modules.

Build with Webpack

Finally, you'll need to build your Javascript assets with Webpack. To do this, simply run npm run dev and you'll be all set!

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