不能 auto-generate 在 Laravel 5.4 中实时击杀

Can't auto-generate slug realtime in Laravel 5.4

我想在用户输入标题时auto-generate slug。

<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>

问题是:

  1. 当我在Title of news中输入文字时,它并没有实时改变。

  2. 因为不是实时变化,所以没有正确保存slug。

示例:

当我在新闻字段 Title 中输入时:Apple iPhone 7 -> 单击按钮保存。字段 slug 不包含任何值。

接下来,我将新闻的 Title 更改为 Apple have plan release IOS 11 -> 单击按钮保存。数据库中的字段 slug 更改为 Apple iPhone 7.

你可以在 gif 上看到:

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

您的控制器:

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();
}

您的看法:

<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>

我没试过,但应该可以。您可能需要适应您的系统,但思路就在这里。