PHP code example of amdadulhaq / unique-slug-laravel

1. Go to this page and download the library: Download amdadulhaq/unique-slug-laravel 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/ */

    

amdadulhaq / unique-slug-laravel example snippets


namespace App\Models;

use AmdadulHaq\UniqueSlug\HasSlug;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasSlug;

    protected $fillable = ['name', 'slug'];
}

Article::create(['name' => 'Hello World']);
// Generates slug: hello-world

Article::create(['name' => 'Hello World']);
// Generates slug: hello-world-1

class Article extends Model
{
    use HasSlug;

    public function getSlugSourceAttribute(): string
    {
        return 'title'; // Generate slug from title field
    }

    public function getSlugNameAttribute(): string
    {
        return 'slug'; // Store slug in slug field
    }

    public function getSlugSeparator(): string
    {
        return '_'; // Use underscore separator
    }
}

// config/slug.php
return [
    'update_on_update' => env('SLUG_UPDATE_ON_UPDATE', false),
    'case' => env('SLUG_CASE', 'lower'),
    'max_length' => env('SLUG_MAX_LENGTH', 255),
    'reserved_slugs' => ['admin', 'dashboard', 'api'],
    'suffix_separator' => env('SLUG_SUFFIX_SEPARATOR', '-'),
    'skip_on_empty' => env('SLUG_SKIP_ON_EMPTY', false),
    '

class Article extends Model
{
    use HasSlug;

    protected function generateCustomSlug(string $source): string
    {
        return 'article-'.strtolower($source);
    }
}

class Article extends Model
{
    use HasSlug;

    public function shouldSkipSlug(): bool
    {
        return $this->published === false;
    }
}

config(['slug.case' => 'upper']);
Article::create(['name' => 'Hello World']);
// Generates slug: HELLO-WORLD

config(['slug.max_length' => 50]);
Article::create(['name' => 'Very Long Title That Should Be Truncated']);
// Truncates slug to 50 characters

config(['slug.reserved_slugs' => ['admin', 'dashboard']]);
Article::create(['name' => 'admin']);
// Generates slug: admin-1

Article::whereSlug('hello-world')->first();
Article::orWhereSlug('another-slug')->get();
Article::whereSlugLike('hello')->get();

class Article extends Model
{
    use HasSlug;
    use \Illuminate\Database\Eloquent\SoftDeletes;
}

// Include soft deleted records in uniqueness check
config(['slug.
bash
php artisan vendor:publish --tag=unique-slug-config