1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Laravel 10 with Spatie Media Library: Error "Call to undefined method...

Discussão em 'Outras Linguagens' iniciado por maxime42, Novembro 7, 2024 às 16:12.

  1. maxime42

    maxime42 Guest

    I'm using Laravel 10 with PHP 8.2 and Spatie Media Library to manage file attachments for my Mail model. When I try to access files from the 'mails' media collection in my controller, I encounter this error:

    BadMethodCallException: Call to undefined method App\Models\Mail::getMediaAttribute()

    I haven't defined a getMediaAttribute() method in my model, so I'm puzzled about why Laravel is trying to call this method. Here’s my current setup with the model and the controller code for fetching associated files:

    Mail Model

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Spatie\MediaLibrary\HasMedia;
    use Spatie\MediaLibrary\InteractsWithMedia;

    class Mail extends Model implements HasMedia
    {
    use HasFactory, SoftDeletes, InteractsWithMedia;

    protected $table = 'mails';

    protected $fillable = [
    'domiciled_id',
    'name',
    'created_at',
    'updated_at',
    'readed_at',
    'deleted_at',
    ];

    public function registerMediaCollections(): void
    {
    $this->addMediaCollection('mails')->useDisk('mails');
    }
    }


    Controller

    use App\Models\Mail;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Crypt;
    use Illuminate\Support\Facades\Storage;
    use Spatie\MediaLibrary\MediaCollections\Models\Media;

    public function index(Request $request)
    {
    $mails = Mail::paginate(10);

    $decryptedMails = $mails->map(function ($mail) {
    // Retrieve media items for the 'mails' collection
    $mediaItems = $mail->getMedia('mails');

    $mail->media = $mediaItems->map(function ($media) {
    // Fetch and decrypt the media file content
    $encryptedContents = Storage::disk($media->disk)->get($media->id . '/' . $media->file_name);
    $decryptedContents = Crypt::decrypt($encryptedContents);

    return [
    'id' => $media->id,
    'file_name' => $media->file_name,
    'mime_type' => $media->mime_type,
    'decrypted_content' => base64_encode($decryptedContents),
    'original_url' => $media->getUrl(),
    ];
    });

    return $mail;
    });

    return response()->json([
    'data' => $decryptedMails,
    'meta' => [
    'total' => $mails->total(),
    'current_page' => $mails->currentPage(),
    'last_page' => $mails->lastPage(),
    'per_page' => $mails->perPage(),
    ],
    ]);
    }


    I'm really stuck on this error and don't understand why it's happening. Could anyone shed light on where this error might be coming from and how to fix it?

    Thanks in advance for your help!

    Continue reading...

Compartilhe esta Página