laravel - 用路由 laravel 助手替换字符路由的最佳方法是什么?
问题描述
我想改进路线生成。实际上,我对我的解决方案并不满意,而且我不在最佳实践路径上。
我需要在刀片中生成一些路线。
- 应该只生成小写的网址
- 我将替换一些字母,例如 ä -> ae
- 解析日期
什么是“最佳实践”?
我尝试直接在刀片文件中执行此操作。
@foreach($foods as $food)
<a href="{{route('food.show', [
'name' => $food->name,
'date' => App\Models\Food::replaceCharacters(Str::lower(Carbon\Carbon::parse($food->urlDate)->isoFormat('DD-MMMM-YYYY')))])}}">
Linkname}}
</a>
@endforeach
解决方案
Laravel 有一些原生助手可以帮助你实现这个目标。主要是Str::slug
方法。
这是它的源代码:
/**
* Generate a URL friendly "slug" from a given string.
*
* @param string $title
* @param string $separator
* @param string|null $language
* @return string
*/
public static function slug($title, $separator = '-', $language = 'en')
{
$title = $language ? static::ascii($title, $language) : $title;
// Convert all dashes/underscores into separator
$flip = $separator === '-' ? '_' : '-';
$title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);
// Replace @ with the word 'at'
$title = str_replace('@', $separator.'at'.$separator, $title);
// Remove all characters that are not the separator, letters, numbers, or whitespace.
$title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', static::lower($title));
// Replace all separator characters and whitespace by a single separator
$title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);
return trim($title, $separator);
}
这个帮助器足以生成一个 SEO 友好的 URL,但这个答案只针对第一个和第二个要点。对于其余部分,我认为最好的解决方案是在您的班级Food
中使用访问器。
这样,当您访问该name
属性或该urlDate
属性时,您可以收到一个已经格式化的字符串。例如:
use Illuminate\Support\Str;
[...]
public function getNameAttribute($value)
{
// Return the slug for a SEO friendly parameter
return Str::slug($value);
}
示例输入:My äwe$oMe food|name
示例输出:my-aweome-foodname
对于日期,您应该只在此代码中添加格式部分。
推荐阅读
- node.js - Angular 安装无法识别节点
- javascript - 如何管理通过 npm 共享的 React 组件中的导入和依赖项
- arrays - 在 C 中使用数组表示法或指针算术获取数组的最后五个值
- java - 错误:从 C# 启动 java jar 时无法访问 jarfile
- spreadjs - 如何遍历特定列中的单元格
- amazon-web-services - 如何在 terraform 中传递 template_file var 部分中的列表而不是字符串
- reactjs - 如何在使用 http-proxy-middleware 时使用代理值?
- azure-service-fabric - 您如何监控 Fabric.exe 和其他 Service Fabric 可执行文件?
- typescript - 如何使用 Selenium 和 Mocha 实现伊斯坦布尔覆盖
- python - 将元素打印到电子邮件正文问题 Python Selenium SMTPLIB