Thursday 9 September 2021

Create new slug in laravel

Use: $this->createSlug($request['title']);   


public function createSlug($title, $id = 0)

    {

        $slug = str_slug($title);

        $allSlugs = $this->getRelatedSlugs($slug, $id);

        if (! $allSlugs->contains('slug', $slug)){

            return $slug;

        }


        $i = 1;

        $is_contain = true;

        do {

            $newSlug = $slug . '-' . $i;

            if (!$allSlugs->contains('slug', $newSlug)) {

                $is_contain = false;

                return $newSlug;

            }

            $i++;

        } while ($is_contain);

    }

    protected function getRelatedSlugs($slug, $id = 0)

    {

        return Posts::select('slug')->where('slug', 'like', $slug.'%')

        ->where('id', '<>', $id)

        ->get();

    }