簡體   English   中英

如何在關系中上傳文件 hasOn<->belongsTo Laravel Backpack

[英]How to upload file in relationship hasOn<->belongsTo Laravel Backpack

可以存儲上傳到相關表的文件嗎? 場景:我在數據庫中有一個usres表和另一個pictures 用戶 Model有以下 function

public function picture()
    {
        return $this->hasOne(Picture::class);
    }

圖片 Model有以下 function。

public function user_picture()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

是否可以將圖片存儲在UserCrudController store() function 的pictures數據庫表(id, user_id, img_path)中?

嘗試這樣的事情

  public function store(Request $request)
    {
      Picture::create([
       'user_id' => // get the user id from $request or auth()->user(),
       'img_path' => $request->file('image')->store('images', 'public'),
      ]);
      return // your view or something  else
    }

假設這是一個需要插入圖像的注冊表單。 除了直接使用Picture model,您還可以這樣做:

public function store(Request $request)
{
    $request->validate(...);

    $user = User::create(...);

    //It will ensure that the image belongs to the user.
    $user->picture()->create([
        'image_path' => $request->file('image')->store('images');
    ])
}

我通過以下步驟解決了這個問題。 根據 Laravel Backpack,我在 Blade 中添加了輸入字段:

@include('crud::fields.upload', ['crud' => $crud, 'field' => ['name' => 'img1', 'label' => 'Image 1', 'type' => 'upload', 'upload'=> true, 'disk'=>'uploads', 'attributes' => ['id' => 'img1', 'capture' => 'user']]])

在此之后,我在用戶 Controller 中添加了 function,如下所示:

$request->validate(['img1' => 'mimes:jpg,png,jpeg|max:5120']);
$fileModel = new Picture;
      if($request->file()) {
           $fileName1 = time().'_'.$request->img1->getClientOriginalName();
           $filePath1 = $request->file('img1')->storeAs('uploads', $fileName1, 'public');
$fileModel->name = time().'_'.$request->img1->getClientOriginalName();
$fileModel->img1 = '/storage/' . $filePath1;
$fileModel->save();
}

通過這些代碼行,我能夠存儲與用戶相關的圖片。

謝謝大家的指導。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM