PHP code example of kodooy / laravel-slug-generator
1. Go to this page and download the library: Download kodooy/laravel-slug-generator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kodooy / laravel-slug-generator example snippets
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique()->index();
$table->timestamps();
});
Schema::table('posts', function (Blueprint $table) {
$table->string('slug')->unique()->index();
});
use Kodooy\SlugGenerator\Traits\Slugable;
class Post extends Model
{
use Slugable;
// The trait will automatically generate slugs from the 'name' attribute
// and use 'slug' as the route key
}
class Post extends Model
{
use Slugable;
// Use different attribute for slug generation
protected function slugableAttribute()
{
return 'title'; // default is 'name'
}
// Preserve existing slugs on update
protected function preserveSlugOnUpdate()
{
return true; // default is false
}
}
// Slug is automatically generated when creating/updating
$post = Post::create([
'title' => 'My Blog Post',
'content' => 'This is the content...'
]);
// Slug will be: 'my-blog-post'
echo $post->slug;
// Generate slug manually
$post = new Post(['title' => 'Another Great Post']);
$post->slug = $post->generateSlug();
// If a slug already exists, it will be made unique:
// "my-post" -> "my-post-1" -> "my-post-2" etc.
$post1 = Post::create(['title' => 'My Post']); // slug: "my-post"
$post2 = Post::create(['title' => 'My Post']); // slug: "my-post-1"
$post3 = Post::create(['title' => 'My Post']); // slug: "my-post-2"
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.