【问题标题】:What is the best way to lowercase, replace characters route with the route laravel helper?用路由 laravel 助手替换字符路由的最佳方法是什么?
【发布时间】:2020-02-12 21:40:06
【问题描述】:

我想改进路由生成。实际上,我对自己的解决方案并不满意,也没有走上最佳实践之路。

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

  • 应该只生成小写的网址
  • 我将替换一些字母,例如 ä -> 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 replace routes lowercase


    【解决方案1】:

    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 类中使用 Accessor

    这样,当您访问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

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

    【讨论】:

    • 谢谢 ||Gala 对 Accessor 的建议对我来说是金块。一切正常。 :)
    • 很高兴听到这个消息:)
    猜你喜欢
    • 1970-01-01
    • 2020-11-26
    • 2012-10-14
    • 2018-04-07
    • 2015-08-14
    • 2021-06-30
    • 2019-08-10
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多