skip to Main Content

In a Laravel 11 project, I have installed Sluggable package to generate slugs in my project (composer require cviebrock/eloquent-sluggable). I have a model called Tag which will store all the tag information in a json column.

Schema::create( 'tags', function( Blueprint $table ){
    $table->id();
    $table->string( 'slug' )->unique();
    $table->json( 'data' );

    $table->dateTime( 'created_at' )->useCurrent();
    $table->dateTime( 'updated_at' )->useCurrentOnUpdate();
    $table->dateTime( 'deleted_at' )->nullable();
} );

The idea is to store in the data column the tag information like this:

{
  "en": "some-tag",
  "es": "un-tag"
}

In my model I have a method to return the attribute ‘originalName’ based on the application locale:


/**
 * Returns the original name of the tag in the defined application locale
 *
 * @return string
 */
public function getOriginalNameAttribute(): string
{
    return data_get( $this->data, config( 'app.locale' ) );
}

Now, I want to define the Sluggable function using this configuration, so I have added the method like this:

/**
 * Return the sluggable configuration array for this model.
 *
 * @return array
 */
public function sluggable(): array
{
    return [
        'slug' => [
            'source' => 'original',
        ],
    ];
}

But I’m getting an error message when I try to create a Tag:

> use AppModelsTag;
> $tag = Tag::create( [ 'data' => [ 'en' => 'Test' ] ] );

   IlluminateDatabaseQueryException  SQLSTATE[HY000]: General error: 1364 Field 'slug' doesn't have a default value (Connection: mysql, SQL: insert into `tags` (`data`, `updated_at`, `created_at`) values ({"es":"Prueba"}, 2024-05-31 11:57:12, 2024-05-31 11:57:12)).

I guess the problem is coming from the Sluggable method, any ideas on how to fix this?

2

Answers


  1. According to your requirements, you want to generate the slug from "originalName" attribute not from an "original" attribute.
    Here’s how your sluggable function should look:

    public function sluggable(): array
    {
      return [
        'slug' => [
          'source' => 'originalName',
        ],
      ];
    }
    
    Login or Signup to reply.
  2. Just a wild guess, did you add $fillable in your Tag model

    protected $fillable = ['data'];
    

    And sluggable should be

    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'originalName',
            ],
        ];
    }
    

    make sure use CviebrockEloquentSluggableSluggable; is called

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search