How to resolve Error Interface "Spatie\MediaLibrary\HasMedia" not found

2.8k views Asked by At

I have installed Spatie Media Library in a Laravel 9 project. Following the document, I have set my User model to implement HasMedia and also use InteractsWithMedia like this

<?php

namespace App\Models;

use Spatie\Image\Manipulations;
use Laravel\Sanctum\HasApiTokens;
use Spatie\MediaLibrary\HasMedia;
use Illuminate\Notifications\Notifiable;
use Spatie\MediaLibrary\InteractsWithMedia;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements HasMedia
{
    use HasApiTokens, HasFactory, Notifiable, InteractsWithMedia;

    // ...
}

I have also been able to upload images locally in my user controller like this

if ($request->has('photo')) {
    $user->addMedia($request->photo)
        ->toMediaCollection('user-photos');
}

After deploying to my staging server, I am getting this error

local.ERROR: Interface "Spatie\MediaLibrary\HasMedia" not found {"exception":"[object] (Error(code: 0): Interface "Spatie\MediaLibrary\HasMedia" not found at .../app/Models/User.php:15)

I ran composer dump-autoload on the server and that has not fixed the error. Why am I getting this error and what possible solutions can I use for resolving this error?

3

There are 3 answers

0
Mena On BEST ANSWER

Fixed it by running these commands php artisan config:cache and php artisan queue:restart.

Turned out that the reason for the error was because queue worker was still using the previously cached environment variables. Both commands ensured the newly set disk in environment file was now available to the queue worker.

1
Gev99 On

Change this

use Spatie\MediaLibrary\HasMedia;

To

use Spatie\MediaLibrary\HasMedia\HasMedia;
1
Hmerman6006 On

Did composer update and php artisan cache:clear but still got the error Undefined type 'Spatie\MediaLibrary\HasMedia'.
Closing VSCode v1.78.2 and opening it resolved the error message.