首页 > 解决方案 > 用路由 laravel 助手替换字符路由的最佳方法是什么?

问题描述

我想改进路线生成。实际上,我对我的解决方案并不满意,而且我不在最佳实践路径上。

我需要在刀片中生成一些路线。

什么是“最佳实践”?

我尝试直接在刀片文件中执行此操作。

@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

标签: laravelreplacerouteslowercase

解决方案


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

对于日期,您应该只在此代码中添加格式部分。


推荐阅读