Ave
Ave

Reputation: 4430

Can't auto-generate slug realtime in Laravel 5.4

I want to auto-generate slug when user input the title.

<div class="form-group">
    <label for="name">Title of News</label>
    <input type="text" class="form-control" id="name" name="name"
            placeholder="Enter your title of news"
            value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>

<div class="form-group">
    <label for="slug">Slug</label>
    <input type="text" class="form-control" id="slug" name="slug"
        placeholder="slug"
        {{!! isFieldSlugAutoGenerator($dataType, $dataTypeContent, "slug") !!}}
        value="@if(isset($news->name)){{ str_slug($news->name, '-') }}@endif">
</div>

<script>
    $('document').ready(function () {

        $('#slug').slugify();
    });
</script>

Problem is:

  1. It does not change real time when I enter text in Title of news.

  2. Because it does not change real time, it doesn't save slug correctly.

Example:

When I input in fields Title of news: Apple iPhone 7 -> click button Save. The fields slug not contain any values.

Next, I change Title of news to Apple have plan release IOS 11 -> click button Save. The fields slug in database change to Apple iPhone 7.

You can see at gif:

http://i.imgur.com/JD0TbG8.gif

Upvotes: 0

Views: 1389

Answers (1)

Treast
Treast

Reputation: 1105

Your controller :

function store(Request $request) {
  $this->validate($request, [
    'title' => 'required'
  ]);

  $news = News::create($request->all());
  $news->slug = str_slug($request->title, '-');
  $news->save();

  return redirect()->back();
}

Your view :

<div class="form-group">
  <label for="name">Title of News</label>
  <input type="text" class="form-control" id="name" name="name"
  placeholder="Enter your title of news"
  value="@if(isset($news->name)){{ old('name', $news->name) }}@else{{old('name')}}@endif">
</div>
<p>The slug will be <span id="slug"></span></p>

<script>
  $('document').ready(function () {

    $(document).on('change', 'input#name', function() {
      var slug = slugify($(this).val());
      $('span#slug').text(slug);
    });

  });

  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
  }
</script>

I didn't try it, but should work. You probably need to adapt to your system, but the idea is here.

Upvotes: 2

Related Questions