AthenaeumAthenaeum
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
Packages
  • next
  • current
  • v9.x
  • v8.x
  • v7.x
  • v6.x
  • v5.x
  • v4.x
  • v3.x
  • v2.x
  • v1.x
Changelog
GitHub
  • Version 6.x

    • Release Notes
    • Upgrade Guide
    • New to this...
    • Contribution Guide
    • Security Policy
    • Code of Conduct
    • Origin
  • ACL

    • Introduction
    • How to install
    • Setup
    • Permissions
    • Roles
    • Users
    • Cached Permissions
  • Audit

    • Audit
    • How to install
    • Setup
    • Recording
    • Events
  • Circuits

    • Circuits
    • How to install
    • Setup
    • Usage
    • Events
  • Collections

    • Collections
    • How to install
    • Summation

      • Summation Collection
      • Items Processor
  • Config

    • Configuration Loader
    • How to install
    • Setup
    • Load Configuration Files
    • Custom File Parsers
  • Console

    • Command and Schedule Registration
    • How to install
    • Setup
    • Commands
    • Schedules
  • Container

    • IoC Service Container
    • How to install
    • Container
    • List Resolver
  • Core

    • Athenaeum Core Application
    • How to install
    • Setup
    • Usage

      • Configuration
      • Service Providers
      • Service Container
      • Events
      • Caching
      • Logging
      • Console
      • Task Scheduling
      • Exception Handling
      • Extending Core Application
      • Testing
  • Database

    • Introduction
    • How to install
    • Models

      • Instantiatable
      • Sluggable
    • Query

      • Criteria (Query Filter)
  • Dto

    • Data Transfer Object (DTO)
    • How to install
    • Create Interface
    • Implement DTO
    • How to use
    • Populate
    • Export
    • Json
    • Serialization
    • Nested DTOs
    • Array DTO
  • ETags

    • ETags
    • How to install
    • Setup
    • Usage
    • Generators

      • Default Generator
      • Custom Generator
    • Eloquent Models
    • Macros
  • Events

    • Register Listeners and Subscribers
    • How to install
    • Setup
    • Listeners
    • Subscribers
  • Filters

    • Search Filter Utilities
    • Prerequisites
    • How to install
    • Setup
    • Processor
    • Filters Builder
    • Predefined Resources

      • Search Processor
      • Sorting Processor
      • Constraints Processor
      • Matching Processor
    • Tip: Create a base builder
  • Flysystem

    • Introduction
    • Database Adapter

      • Introduction
      • How to install
      • Setup
      • Data Deduplication
      • MIME-Type Detection
  • Http

    • Api

      • Http API
      • How to install
      • Setup
      • Resources

        • Introduction
        • Timestamps
        • Self-Link
        • Relations
        • Registrar
      • Middleware

        • Introduction
        • Request Must Be Json
        • Capture Fields To Select
    • Clients

      • Http Clients
      • How to install
      • Setup
      • Basic Usage
      • Available Methods

        • Fluent Api
        • Protocol Version
        • Base Uri
        • Http Method and Uri
        • Headers
        • Accept & Content-Type
        • Authentication
        • Http Query
        • Payload Format
        • Payload
        • Attachments
        • Cookies
        • Response Expectations
        • Middleware
        • Conditions
        • Criteria
        • Redirects
        • Timeout
        • Debugging
        • Logging
        • Driver Options
        • Driver
      • Http Query Builder

        • Introduction
        • Select
        • Where
        • Dates
        • Include
        • Pagination
        • Sorting
        • Raw Expressions
        • Custom Grammar
    • Cookies

      • Http Cookies
      • How to install
      • Usage
    • Messages

      • Http Messages
      • How to install
      • Serializers
  • Maintenance

    • Modes

      • Maintenance Modes
      • How to install
      • Setup
      • Basic Usage
      • Available Drivers
  • Mime Types

    • MIME-Types
    • How to install
    • Setup
    • Usage
    • Drivers

      • Available Drivers
      • File Info
  • Properties

    • Properties Overload
    • How to install
    • Usage
    • Naming Convention
    • Properties Visibility
  • Redmine

    • Redmine Api Client
    • How to install
    • Setup
    • General Usage

      • Supported Operations
      • Fetch list of resources
      • Find
      • Fetch
      • Create new record
      • Update existing record
      • Delete existing record
      • Relations
    • Available Resources

      • Predefined Resources
      • Attachments
      • Enumerations
      • Issue Relations
      • Users
      • User Groups
      • Roles
      • Project Memberships
      • Versions (Milestones)
      • Issue Categories
      • Trackers
  • Service

    • Service Registrar
    • How to install
    • How to use
  • Streams

    • Streams
    • How to install
    • Setup
    • How to use

      • Introduction
      • Open and Close
      • Raw Resource
      • Seeking
      • Reading
      • Writing
      • Size
      • Truncate
      • Flush
      • Hash
      • MIME-Type
      • Output
      • Locking
      • Transactions
      • Meta
      • Misc
  • Support

    • Introduction
    • How to install
    • Laravel Aware-of Helpers

      • How to use
      • Enforce Via Interface
      • Custom Default
      • Pros and Cons
      • Available Helpers
    • Aware-of Properties

      • Generator
      • Available Aware-of Helpers
    • Live Templates
  • Testing

    • Introduction
    • How to install
    • Test Cases
    • Testing Aware-of Helpers
  • Utils

    • Introduction
    • How to install
    • Array
    • Duration
    • Json
    • Math
    • Memory
    • Method Helper
    • Invoker
    • Populatable
    • String
    • Version
  • Validation

    • Introduction
    • How to install
    • Setup
    • Rules

      • Alpha-Dash-Dot
      • Semantic Version
You are viewing documentation for an outdated version. It is no longer supported!

Sluggable

If your model uses a slug, then the Sluggable interface and Slugs concern trait may offer some common utility methods.

  • How to use
  • Slug attribute name
    • Alternative
  • Find by slug
  • Find by slug or fail
  • Find many by slugs
  • Find or create by slug
  • Query Scopes
    • whereSlug
    • whereSlugIn
  • Soft-deleted vs. Finding by slugs
  • Onward

How to use

use Aedart\Contracts\Database\Models\Sluggable;
use Aedart\Database\Models\Concerns;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Sluggable
{
    use Concerns\Slugs;
}

Slug attribute name

By default, the Slugs concern will assume that your model's slug attribute is named "slug". If this is not the case, you may customise this inside your model, by adding the $slugKey property.

use Aedart\Contracts\Database\Models\Sluggable;
use Aedart\Database\Models\Concerns;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Sluggable
{
    use Concerns\Slugs;
    
    protected string $slugKey = 'post-url';
}

Alternative

Alternatively, you may specify the slug attribute name by overwriting the getSlugKeyName() method.

use Aedart\Contracts\Database\Models\Sluggable;
use Aedart\Database\Models\Concerns;
use Illuminate\Database\Eloquent\Model;

class Post extends Model implements Sluggable
{
    use Concerns\Slugs;
    
    public function getSlugKeyName(): string
    {
        return 'post-url';
    }
}

Find by slug

The findBySlug() allows you to find a record that matches given slug. The method will return the first matching record or null, if none was found.

$post = Post::findBySlug('january-hits');

Find by slug or fail

Use findBySlugOrFail() method to ensure that a record exists or fail by throwing a ModelNotFoundException¹ exception.

$post = Post::findBySlugOrFail('sprint-soundtracks');

¹: \Illuminate\Database\Eloquent\ModelNotFoundException

Caution

If your model does not guarantee unique slugs, and multiple records are found by the findBySlugOrFail() method, then an \Illuminate\Database\MultipleRecordsFoundException is thrown.

Find many by slugs

To find multiple records by their slugs, you can use the findManyBySlugs() method. The method returns an Eloquent Collection with models matching the given slugs.

$posts = Post::findManyBySlugs([
    'sprint-soundtracks',
    'january-hits',
    'december-greatest-hits'
]);

Find or create by slug

The findOrCreateBySlug() method attempts to find a record matching given slug. If none can be found, it will create a new record with provided attributes and return the model instance.

$post = Post::findOrCreateBySlug('april-morning-tunes', [
    'author' => 'Christina Stein',
    'content' => 'Not nirvana or shangri-la, experience the heaven.'
]);

Query Scopes

The following local query scope methods are offered:

whereSlug

Matches against given slug.

$post = Post::query()
            ->whereSlug('summer-hits')
            ->first();

whereSlugIn

Matches against a list of slugs.

$posts = Post::query()
            ->whereSlugIn([ 'autumn-hits', 'evening-soundtrack' ])
            ->get();

Soft-deleted vs. Finding by slugs

If your model supports soft-deleting, and you attempt to find a record by a slug that has been soft deleted, then none of the "find by slug" methods are going to return a match. To query models that have been soft deleted, you must make use of Eloquent's withTrashed() method.

$post = Post::withTrashed()
            ->whereSlug('my-deleted-hit')
            ->first();

Onward

For additional information, please review the source code of the \Aedart\Database\Models\Concerns\Slugs trait.

Edit page
Last Updated: 16/02/2023, 09:10
Contributors: Alin Eugen Deac, alin
Prev
Instantiatable