With the help of AI, I created this slug driver that will change the discussion URL slug.
/d/37500-the-topic-url
to
/d/the-topic-url-37500 - {$slug}-{$discussion->id}
It works just fine when posting new discussions, and I am able to click on the discussion title and access the post.
However, when you open a new tab and try to load the URL, that throws a 404 error.
Any ideas?
Here is my code that i use in my extend.php file:
To use this, go administration -> basics and change "Slug Driver: Flarum\Discussion\Discussion" to "slugFirst"
use Flarum\Discussion\Discussion;
use Flarum\Discussion\DiscussionRepository;
use Flarum\Http\SlugDriverInterface;
use Flarum\User\User;
use Flarum\Database\AbstractModel;
use Illuminate\Support\Str;
class SlugFirstDriver implements SlugDriverInterface
{
protected $discussions;
public function __construct(DiscussionRepository $discussions)
{
$this->discussions = $discussions;
}
public function toSlug($discussion): string
{
$slug = $discussion->slug ?: Str::slug($discussion->title);
return "{$slug}-{$discussion->id}";
}
public function fromSlug(string $slug, User $actor): AbstractModel
{
$lastDash = strrpos($slug, '-');
if ($lastDash === false) {
throw new \InvalidArgumentException("Invalid discussion slug: $slug");
}
$id = substr($slug, $lastDash + 1);
return $this->discussions->findOrFail((int) $id, $actor);
}
}
return [
(new Extend\ModelUrl(Discussion::class))
->addSlugDriver('slugFirst', SlugFirstDriver::class),
];