hjortur17
265
13
General

Slug

Posted 1 month ago by hjortur17

Hello, I'm trying to use slug for my threads. I have a script to check if the slug and then add to it a number if somewhere in my forum a thread has the same title and slug. For example:

foo-bar
foo-bar-2
foo-bar-3

And here is my test:

/** @test */
    function a_thread_requires_a_unique_slug()
    {
        $this->signIn();

        $thread = create('App\Thread', ['title' => 'Foo Title', 'slug' => 'foo-title']);

        $this->assertEquals($thread->fresh()->slug, 'foo-title');

        $this->post('/fréttir', $thread->toArray());

        $this->assertTrue(Thread::whereSlug('foo-title-2')->exists());

        $this->post('/fréttir', $thread->toArray());

        $this->assertTrue(Thread::whereSlug('foo-title-3')->exists());
    }

And here is my function inside Thread.php

public function getRouteKeyName()
    {
        return 'slug';
    }

    public function setSlugAttribute($value)
    {
        if (static::whereSlug($slug = str_slug($value))->exists()) {
            $slug = $this->incrementSlug($slug);
        }
    
        $this->attributes['slug'] = $slug;
    }

    protected function incrementSlug($slug)
    {
        $max = static::whereTitle($this->title)->latest('id')->value('slug');
        
        if (is_numeric($max[-1])) {
            return preg_replace_callback('/(\d+)$/', function ($matches) {
                return $matches[1] + 1;
            }, $max);
        }
    
        return "{$slug}-2";
    }

Please sign in or create an account to participate in this conversation.