Laravel中的多个图像上传调整以添加其他字段

时间:2019-05-31 08:48:20

标签: laravel laravel-5.8

我需要上传多张图片。下面的代码运行良好。这是使用干预图像插件。我正在尝试自定义此代码,以将另一个字段(即ForeignKey值)添加到此图像模型的父级。 $ request的值来自表单。如何将其与图像一起保存?
值是:

  

adb start-server

如何调整以下方法,以使保存也包括该vehicle_id?

$request('vehicle_id')

1 个答案:

答案 0 :(得分:0)

我找到了解决方法

public function uploadImage(Request $request) 
    {   
        $request->validate([
            'image' => 'required',
            'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'vehicle' => 'required'
        ]);

    //check if image exist
    if ($request->hasFile('image')) {
        $images = $request->file('image');

        // create new directory for uploading image if doesn't exist
        if( ! File::exists('images/'.auth()->user()->id.'/')) {
            $org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
        }

        // loop through each image to save and upload
        foreach($images as $key => $image) {
            //create new instance of Photo class
            $newPhoto = new $this->photo;
            //get file name of image  and concatenate with 4 random integer for unique
            $filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
            //path of image for upload
            $org_path = 'images/'.auth()->user()->id.'/' . $filename;

            $newPhoto->image     = 'images/'.auth()->user()->id.'/' . $filename;
            $newPhoto->vehicle = $request->input('vehicle');
            //don't upload file when unable to save name to database
            if ( ! $newPhoto->save()) {
                return false;
            }
            // upload image to server
           Image::make($image)->fit(900, 500, function ($constraint) {
                   $constraint->upsize();
               })->save($org_path);


        }
    }

    return redirect('/home')->with('success','Images Uploaded');