user9985808
user9985808

Reputation:

How to use Laravel Blade in JS (PHP)

I am developing a blog project in Laravel 5.6. I am using the Laravel built-in function called str_slug() to convert titles into slugs and JavaScript to auto generate the slugs using JavaScript's keyup function. Here's my code:

var postTitle = $('#post-title');
var postSlug = $('#post-slug');
postTitle.keyup(function() {
    postSlug.val({{ str_slug(postTitle.val()) }});
});

However, it's throwing an error of unknown constant. Can anyone tell me how to what I want? I am new to Laravel.

Upvotes: 1

Views: 1008

Answers (2)

Xixis
Xixis

Reputation: 909

You can use the html markup to get this done. In the html mark up create a hidden input and put in the value of str_str() operation on the post-title and in your js set the post-slug input value to that on keyup.

<input type="text" id="post-title" value="{{$title}}">
<input type="hidden" id="hidden-post-title" value="{{str_slug($title)}}">

var postTitle = $('#post-title');
var postSlug = $('#post-slug');
postTitle.keyup(function() {
    postSlug.val($('#hidden-post-title').val());
});

Upvotes: -1

Brian Lee
Brian Lee

Reputation: 18197

Here's a simple function to create a slug in JS:

function slugify(text)
{
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text
}

Source Gist

Upvotes: 3

Related Questions