1. Go to this page and download the library: Download mimachh/slugme 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/ */
mimachh / slugme example snippets
composer
use Mimachh\Slugme\Contracts\Sluggable;
use Mimachh\Slugme\Concerns\HasSlug;
use Illuminate\Database\Eloquent\Model;
class Post extends Model implements Sluggable
{
use HasSlug;
// Define the column to store the slug
public function slugColumn(): string {
return 'slug';
}
// Define the attribute to generate the slug from
public function slugAttribute(): string {
return 'title';
}
}
public static function generateUniqueSlug(string $attribute): string {
// Custom slug generation logic here
}
$post = new Post();
$post->title = 'My Awesome Post';
$post->save(); // This will automatically generate a slug and save it in the `slug` column.
$post->title = 'My Updated Awesome Post';
$post->save(); // This will update the slug accordingly.
use Mimachh\Slugme\Services\SlugGenerator;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'slug'];
public static function boot()
{
parent::boot();
// Automatically generate a unique slug when creating a new model
static::creating(function ($post) {
$post->slug = SlugGenerator::generateUniqueSlug($post->title, Post::class);
});
// Automatically regenerate the slug if the title is updated
static::updating(function ($post) {
if ($post->isDirty('title')) {
$post->slug = SlugGenerator::generateUniqueSlug($post->title, Post::class, $post->id);
}
});
}
}
use Mimachh\Slugme\Services\SlugGenerator;
// Creating a new post with manual slug generation
$post = new Post();
$post->title = 'My Awesome Post';
$post->slug = SlugGenerator::generateUniqueSlug($post->title, Post::class); // Generate slug manually
$post->save();
$post = Post::find(1);
$post->title = 'Updated Post Title';
$post->slug = SlugGenerator::generateUniqueSlug($post->title, Post::class, $post->id); // Pass the current ID to exclude it
$post->save();
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('slug')->unique(); // Add this column
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('posts');
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.