padosoft/laravel-sluggable
Composer 安装命令:
composer require padosoft/laravel-sluggable
包简介
Generate slugs when saving Eloquent models
README 文档
README
This package provides a trait that will generate a unique slug when saving any Eloquent model.
NOTE: This package is based on spatie/laravel-sluggable but with some adjustments for me and few improvements. Here's a major changes:
- Added the ability to specify a source field through a model relation with dot notation. Ex.: ['category.name'] or ['customer.country.code'] where category, customer and country are model relations.
- Added the ability to specify multiple fields with priority to look up the first non-empty source field. Ex.: In the example above, we set the look up to find a non empty source in model for slug in this order: title, first_name and last_name. Note: slug is set if at least one of these fields is not empty:
SlugOptions::create()->generateSlugsFrom([ 'title', ['first_name', 'last_name'], ])
- Added option to set the behaviour when the source fields are all empty (thrown an exception or generate a random slug).
- Remove the abstract function getSlugOptions() and introduce the ability to set the trait with zero configuration with default options. The ability to define getSlugOptions() function in your model remained.
- Added option to set slug separator
- Some other adjustments and fix
##Overview
$model = new EloquentModel(); $model->name = 'activerecord is awesome'; $model->save(); echo $model->slug; // outputs "activerecord-is-awesome"
The slugs are generated with Laravels str_slug method, whereby spaces are converted to '-'.
##Requires
- php: >=7.0.0
- illuminate/database: ^5.0
- illuminate/support: ^5.0
Installation
You can install the package via composer:
$ composer require padosoft/laravel-sluggable
Usage
Your Eloquent models should use the Padosoft\Sluggable\HasSlug trait and the Padosoft\Sluggable\SlugOptions class.
The trait shipping with ZERO Configuration if your model contains the slug attribute and one of the fields specified in getSlugOptionsDefault().
If the zero config not for you, you can define getSlugOptions() method in your model.
Here's an example of how to implement the trait with zero configuration:
<?php namespace App; use Padosoft\Sluggable\HasSlug; use Illuminate\Database\Eloquent\Model; class YourEloquentModel extends Model { use HasSlug; }
Here's an example of how to implement the trait with implementation of getSlugOptions():
<?php namespace App; use Padosoft\Sluggable\HasSlug; use Padosoft\Sluggable\SlugOptions; use Illuminate\Database\Eloquent\Model; class YourEloquentModel extends Model { use HasSlug; /** * Get the options for generating the slug. */ public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->generateSlugsFrom('name') ->saveSlugsTo('slug'); } }
Want to use multiple field as the basis for a slug? No problem!
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->generateSlugsFrom(['first_name', 'last_name']) ->saveSlugsTo('slug'); }
Want to use relation field as the basis for a slug? No problem!
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->generateSlugsFrom('category.name') ->saveSlugsTo('slug'); }
where category is a relation in your model:
public function category() { return $this->belongsTo('\App\Category', 'category_id'); }
If you want to use a specific language for the slug creation
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->slugifyUseLanguage('jp') ->saveSlugsTo('slug'); }
If you want to use a specific convertion dictionary
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->slugifyUseDictionary(['@'=>'at','['=>'quad']) ->saveSlugsTo('slug'); }
It support chaining for relation so you can also pass a customer..
You can also pass a callable to generateSlugsFrom.
By default the package will generate unique slugs by appending '-' and a number, to a slug that already exists.
You can disable this behaviour by calling allowDuplicateSlugs.
By default the package will generate a random 50char slug if all source fields are empty.
You can disable this behaviour by calling disallowSlugIfAllSourceFieldsEmpty
and set the random string char lenght by calling randomSlugsShouldBeNoLongerThan.
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->generateSlugsFrom('name') ->saveSlugsTo('url') ->allowDuplicateSlugs() ->disallowSlugIfAllSourceFieldsEmpty() ; }
You can also put a maximum size limit on the created slug and/or the lenght of random slug:
public function getSlugOptions() : SlugOptions { return SlugOptions::create() ->generateSlugsFrom('name') ->saveSlugsTo('url') ->slugsShouldBeNoLongerThan(50) ->randomSlugsShouldBeNoLongerThan(20); }
The slug may be slightly longer than the value specified, due to the suffix which is added to make it unique.
You can also override the generated slug just by setting it to another value then the generated slug.
$model = EloquentModel:create(['name' => 'my name']); //url is now "my-name"; $model->url = 'my-custom-url'; $model-save(); $model->name = 'changed name'; $model->save(); //url stays "my name" //if you reset the slug and recall save it will regenerate the slug. $model->url = ''; $model-save(); //url is now "changed-name";
Custom slug (i.e.: manually set slug url)
If you want a custom slug write by hand, use the saveCustomSlugsTo() method to set the custom field:
->saveCustomSlugsTo('url-custom')
Then, if you set the url-custom attribute in your model, the slug field will be set to same value.
In any case, check for correct url and uniquity will be performed to custom slug value.
Example:
$model = new class extends TestModel { public function getSlugOptions(): SlugOptions { return parent::getSlugOptions()->generateSlugsFrom('name') ->saveCustomSlugsTo('url_custom'); } }; $model->name = 'hello dad'; $model->url_custom = 'this is a custom test'; $model->save(); //the slug is 'this-is-a-custom-test' and not , 'hello-dad';
SluggableScope Helpers
The package included some helper functions for working with models and their slugs. You can do things such as:
$post = Post::whereSlug($slugString)->get(); $post = Post::findBySlug($slugString); $post = Post::findBySlugOrFail($slugString);
Change log
Please see CHANGELOG for more information what has changed recently.
Testing
$ composer test
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email instead of using the issue tracker.
Credits
About Padosoft
Padosoft (https://www.padosoft.com) is a software house based in Florence, Italy. Specialized in E-commerce and web sites.
License
The MIT License (MIT). Please see License File for more information.
padosoft/laravel-sluggable 适用场景与选型建议
padosoft/laravel-sluggable 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 15.13k 次下载、GitHub Stars 达 4, 最近一次更新时间为 2016 年 07 月 09 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「padosoft」 「laravel-sluggable」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 padosoft/laravel-sluggable 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 padosoft/laravel-sluggable 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 padosoft/laravel-sluggable 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Generate slugs when saving Eloquent models
Laravel package for automatic upload handling with trait
Laravel Laravel Package for beautifull JS notification.
Notification system for laravel
Implementation for Laravel of the presenter design pattern.
Presentation and Formatting helper with nice fluent interface.
统计信息
- 总下载量: 15.13k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 5
- 点击次数: 8
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2016-07-09