【问题标题】:BadMethodCallException: Call to undefined method App\Models\User::getFirstMedia()BadMethodCallException:调用未定义的方法 App\Models\User::getFirstMedia()
【发布时间】:2021-01-03 15:28:44
【问题描述】:

我正在努力:

$this->assertFileExists($user->getFirstMedia()->getPath()); 在我的测试中。但是当我运行它时,我得到了这个错误:

BadMethodCallException: Call to undefined method App\Models\User::getFirstMedia().

我愿意:

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

我也这样做:

class AssortmentTest extends TestCase implements hasMedia
{
    use RefreshDatabase;
    use InteractsWithMedia;

据我所知,我正在使用正确的特征。我在这里做错了什么?

编辑:

我的测试:

public function testUserCanUploadFile()
    {
        $this->withoutExceptionHandling();
        $user = $this->signIn();

        Storage::fake('public'); //Mock a disk
        $file = UploadedFile::fake()->image('test.jpg'); //Upload a fake image.

        $assortmentAttributes = Assortment::factory()->raw(); // Use the assortment factory.
        $assortmentAttributes['image_path'] = $file; // Add a additional field in the assortment factory.

        $this->post(route('assortments.store'), $assortmentAttributes)->assertRedirect(); // Post the fields to the assortmentcontroller store method.
        //Storage::disk('public')->assertExists($file->hashName()); // Check if the field exists.

        $this->assertFileExists($user->getFirstMedia()->getPath());
    }

我的存储方法控制器代码:

if ($request->hasFile('image')) {
            $image = $request->file('image'); //request the file
            $fileName = md5_file($image . microtime()) . '.' . $image->getClientOriginalExtension(); //use md5 for security reasons and get the extension.
            $image->storeAs('', $fileName, 'public'); //store the file in the public folder disk.
        } 
        
         if ($request->wantsJson()) {
             return response([], 204);
        }

【问题讨论】:

  • 不应该是implements HasMedia而不是implements hasMedia吗?
  • 不,我已经试过了。
  • "据我所知,我使用了正确的特征" 我们可以看到它们吗?你的User 模型是什么样的?
  • @Parsa_237 根据docsimplements HasMedia

标签: php laravel laravel-medialibrary


【解决方案1】:

您在TestCase 中实现您的特征,这是不正确的。如果您正在访问您的用户媒体,您应该在 User.php 模型类上实现特征,它位于 app/User.phpapp/Models/User.php

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class User extends Authenticatable implements HasMedia {
   use InteractsWithMedia;
}

【讨论】:

  • 嗨,我把代码放在我的User 模型中。它确实有效,但返回以下错误:Error: Call to a member function getPath() on null。我相信这与包裹无关?
  • 您需要显示更多代码或堆栈跟踪,让我们看看有什么问题?
  • 当然,请检查我的问题中的编辑。
  • 可能是您的控制器代码不起作用且未附加媒体。调用控制器后,最好执行 response->assertOk();确保控制器调用没有失败
猜你喜欢
  • 2021-03-19
  • 2021-06-24
  • 2022-12-09
  • 1970-01-01
  • 2021-06-21
  • 2023-02-06
  • 2020-12-29
  • 2022-01-26
  • 1970-01-01
相关资源
最近更新 更多