根据Laravel中的特定功能自动更新Slug字段值



我正在使用Laravel 6构建一个博客系统,我有一个函数来生成一个唯一的Slug。

我想做的是创建帖子表单中的一个字段,当我在标题字段上键入时,这个字段将自动更新。

我想在键入标题字段时,从Slug Function生成Slug字段值。

那么,有没有什么方法可以使用jQuery或其他东西来做到这一点呢?

Slug函数

public function slug($string, $separator = '-') {
if (is_null($string)) {
return "";
}
$string = trim($string);
$string = mb_strtolower($string, "UTF-8");
$string = preg_replace("/[^a-z0-9_sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
$string = preg_replace("/[s-]+/", " ", $string);
$string = preg_replace("/[s_]/", $separator, $string);
return $string;
}

存储方法

public function store(Request $request)
{
$this->validate($request, array(
'title'         => 'required|max:255',
'body'          => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}

查看

<form action="{{ route('posts.store') }}" method="post">
@csrf
<div class="row gutters-tiny">
<div class="col-md-7">
<div class="block block-rounded block-themed">
<div class="block-header bg-gd-primary">
<div class="block-options">
<button type="submit" class="btn btn-sm btn-alt-primary">
<i class="fa fa-save mr-5"></i> Save
</button>
</div>
</div>
<div class="block-content block-content-full">
<div class="form-group row">
<label class="col-12" for="ecom-product-name">Title</label>
<div class="col-12">
<input type="text" class="form-control" id="title" name="title"  value="">
</div>
</div>
<div class="form-group row">
<label class="col-12">Body</label>
<div class="col-12">
<textarea class="form-control" id="body" name="body" rows="8"></textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</form>

You'v要更改代码中的这两个函数,我将在laravel项目中尝试此代码。

Slug函数:

public function slug($string, $separator = '-') {
if (is_null($string)) {
return "";
}
$string = trim($string);
$string = mb_strtolower($string, "UTF-8");
$string = preg_replace("/[^a-z0-9_sءاأإآؤئبتثجحخدذرزسشصضطظعغفقكلمنهويةى]#u/", "", $string);
$string = preg_replace("/[s-]+/", " ", $string);
$string = preg_replace("/[s_]/", $separator, $string);
return slug_str($string).'-'.rand(0,9);
}

存储方式:

public function store(Request $request)
{
$this->validate($request, array(
'title'         => 'required|max:255',
'body'          => 'required',
));
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->slug = slug($request->input('title'));
$post->save();
return redirect('admin/posts')->with('success', 'post is successfully saved');
}

参考网址:点击收听

相关内容

  • 没有找到相关文章

最新更新