phplaravelslug

Laravel spatie translatable and sluggable (translatable slugs)


So I have just discovered the package laravel-sluggable and I am trying to setup translatable slugs. I got an error with the route model binding, error 404. So I created a simple migration, simple model and simple route, but the same error occurs. My database supports json.

My migration:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->json('name');
        $table->json('slug');
        $table->timestamps();
    });
}

My model:

<?php

namespace App\Models;

use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Spatie\Sluggable\HasTranslatableSlug;

class Post extends Model
{
    use HasTranslations, HasTranslatableSlug;

    public $translatable = ['name', 'slug'];

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }
}

Artisan tinker shows me that the Post I created has been added and it looks like this:

+"name": "{"nl": "test"}",
+"slug": "{"nl": "test"}",

My locale is indeed nl at the moment but browsing to the following route gives me a 404 error:

use App\Models\Post;

Route::get('posts/{post}', function (Post $post) {
    dd($post);
});

My question is, what am I missing here? Regular slugs with this package are working like a charm. Also, the translatable package is working like a charm. It is just the translated slugs I am having an issue with right now.


Solution

  • With a fresh Laravel 9 installation it worked like a charm and thus I have upgraded my Laravel 8 to Laravel 9 and it is working now.