0

我正在尝试使用 Spatie 的媒体库(v9)保存我上传的文件,但不知何故我无法将图像保存在我的媒体表和我的存储文件夹中。当我 dd() 请求它找到文件和它需要的所有信息时,我错过了什么?

这是我的控制器存储方法:

 public function store(Request $request, User $user) {

    
    $validationToken = Str::random(32);

    $user->create([
        'name' => $request->name,
        'email' => $request->email,
        'description' => $request->description,
        'validation_token' => $validationToken
    ]);

    if($request->file('avatar')) {
        // persists the uploaded file into the media table
        $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');

        // fills the avatar column in user table with image path
        $user->update(['avatar' => $request->file('avatar')]);
    }

    session()->flash('message', 'L`utilisateur a bien été créé');
    return redirect()->back();
}

}

还有我的模特

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


public function registerMediaConversions(Media $media = null): void
{
    $this->addMediaConversion('thumb')
        ->width(368)
        ->height(232)
        ->sharpen(10);
}

// allows to delete previous avatars when new one is submitted with singleFile() method
public function registerMediaCollections(): void
{
    $this
        ->addMediaCollection('avatars')
        ->singleFile();
}
}

预先感谢您的帮助

4

1 回答 1

0

好吧,刚刚找到答案,我真的很接近。

addMediaFromRequest() 方法必须在 $user->create() 而不是模型本身上调用。

public function store(Request $request, User $user) {


    $validationToken = Str::random(32);

    $createUser = $user->create([
        'name' => $request->name,
        'email' => $request->email,
        'description' => $request->description,
        'validation_token' => $validationToken
    ]);

    if($request->file('avatar')) {
        $createUser->addMediaFromRequest('avatar')->toMediaCollection('avatars');
        $createUser->update(['avatar' => $request->file('avatar')]);
    }
}
于 2020-11-15T19:53:28.807 回答