I am trying to use the spatie "laravel-media library 10" with laravel 9 and models using uuids.
The media will be attached to the users. So my user class is :
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class User extends Authenticatable implements HasMedia
{
use HasFactory, Notifiable, HasUuid, HasCreatedUpdatedBy;
use InteractsWithMedia;
public $incrementing = false;
protected $keyType = 'string';
As my user uses uuid for the key, I must declare using my own model (see the spatie documentation here
And so I added a class "Media" :
namespace App\Models;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;
class Media extends BaseMedia
{
protected $primaryKey = 'uuid';
protected $keyType = 'string';
public $incrementing = false;
// ...
}
And I declared it in the config "media-library.php" file :
/*
* The fully qualified class name of the media model.
*/
//'media_model' => Spatie\MediaLibrary\MediaCollections\Models\Media::class,
'media_model' => App\Models\Media::class,
In the UserController, I try to associate the uploaded image to an user like that :
$user->addMedia($request->image_user)->toMediaCollection('images_user');
I cleared the caches, restarted the server etc... And I have still this error :
SQLSTATE[22P02]: Invalid text representation: 7 ERREUR: syntaxe en entrée invalide pour l'entier : « 7f3c4d07-1e0b-4897-b3cf-8d8f9fca7296 » (SQL: select max("order_column") as aggregate from "media" where "model_type" = App\Models\User and "model_id" = 7f3c4d07-1e0b-4897-b3cf-8d8f9fca7296)
It means that the library still considers that my user key is an integer. What can I do more ?
EDIT
I modified the migration file pour the media table :
before :
Schema::create('media', function (Blueprint $table) {
$table->bigIncrements('id');
$table->morphs('model');
after :
Schema::create('media', function (Blueprint $table) {
$table->bigIncrements('id');
$table->uuidMorphs('model');
And now all works fine. But was it the good method ?