在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):spatie/laravel-sluggable开源软件地址(OpenSource Url):https://github.com/spatie/laravel-sluggable开源编程语言(OpenSource Language):PHP 100.0%开源软件介绍(OpenSource Introduction):Generate slugs when saving Eloquent modelsThis package provides a trait that will generate a unique slug when saving any Eloquent model. $model = new EloquentModel();
$model->name = 'activerecord is awesome';
$model->save();
echo $model->slug; // outputs "activerecord-is-awesome" The slugs are generated with Laravels Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website. Support usWe invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products. We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall. InstallationYou can install the package via composer: composer require spatie/laravel-sluggable UsageYour Eloquent models should use the The trait contains an abstract method Your models' migrations should have a field to save the generated slug to. Here's an example of how to implement the trait: namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\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');
}
} With its migration: use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateYourEloquentModelTable extends Migration
{
public function up()
{
Schema::create('your_eloquent_models', function (Blueprint $table) {
$table->increments('id');
$table->string('slug'); // Field name same as your `saveSlugsTo`
$table->string('name');
$table->timestamps();
});
}
} Using slugs in routesTo use the generated slug in routes, remember to use Laravel's implicit route model binding: namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\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');
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
} Using multiple fields to create the slugWant 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');
} Customizing slug generationYou can also pass a 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 public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->allowDuplicateSlugs();
} Limiting the length of a slugYou can also put a maximum size limit on the created slug: public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->slugsShouldBeNoLongerThan(50);
} The slug may be slightly longer than the value specified, due to the suffix which is added to make it unique. You can also use a custom separator by calling public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->usingSeparator('_');
} Setting the slug languageTo set the language used by public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->usingLanguage('nl');
} Overriding slugsYou can also override the generated slug just by setting it to another value than the generated slug. $model = EloquentModel::create(['name' => 'my name']); //slug is now "my-name";
$model->slug = 'my-custom-url';
$model->save(); //slug is now "my-custom-url"; Prevents slugs from being generated on some conditionsIf you don't want to create the slug when the model has a state, you can use the public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->skipGenerateWhen(fn () => $this->state === 'draft');
} Prevent slugs from being generated on creationIf you don't want to create the slug when the model is initially created you can set use the public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnCreate();
} Prevent slug updatesSimilarly, if you want to prevent the slug from being updated on model updates, call public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
} This can be helpful for creating permalinks that don't change until you explicitly want it to. $model = EloquentModel::create(['name' => 'my name']); //slug is now "my-name";
$model->save();
$model->name = 'changed name';
$model->save(); //slug stays "my-name" Regenerating slugsIf you want to explicitly update the slug on the model you can call Preventing overwritesYou can prevent slugs from being overwritten. public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->preventOverwrite();
} Using scopesIf you have a global scope that should be taken into account, you can define this as well with public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->extraScope(fn ($builder) => $builder->where('scope_id', $this->scope_id));
} Integration with laravel-translatableYou can use this package along with laravel-translatable to generate a slug for each locale. Instead of using the namespace App;
use Spatie\Sluggable\HasTranslatableSlug;
use Spatie\Sluggable\SlugOptions;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasTranslations, HasTranslatableSlug;
public $translatable = ['name', 'slug'];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
} For slugs that are generated from a callable, you need to instantiate the namespace App;
use Spatie\Sluggable\HasTranslatableSlug;
use Spatie\Sluggable\SlugOptions;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasTranslations, HasTranslatableSlug;
public $translatable = ['name', 'slug'];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::createWithLocales(['en', 'nl'])
->generateSlugsFrom(function($model, $locale) {
return "{$locale} {$model->id}";
})
->saveSlugsTo('slug');
}
} Implicit route model bindingYou can also use Laravels implicit route model binding inside your controller to automatically resolve the model. To use this feature, make sure that the slug column matches the namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
class YourEloquentModel extends Model
{
use HasTranslations, HasTranslatableSlug;
public $translatable = ['name', 'slug'];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
} ChangelogPlease see CHANGELOG for more information what has changed recently. Testingcomposer test ContributingPlease see CONTRIBUTING for details. SecurityIf you've found a bug regarding security please mail [email protected] instead of using the issue tracker. CreditsLicenseThe MIT License (MIT). Please see License File for more information. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论