0

我想从用户那里获取图像然后重命名它,然后我想将重命名的图像名称保存到数据库中。这是我的控制器代码。我正在使用干预包。重命名后我可以将照片正确保存到目标文件夹,但重命名后我无法将照片的名称保存到我的数据库中。代码是什么?

public function store(UserRequest $request)
    {
        $farmer = User::create([
            'name'            =>  $request->name,
            'phone'           =>  $request->phone,
            'address'         =>  $request->address,
            'nid'             =>  $request->nid,
            'dob'             =>  $request->dob,
            'remarks'         =>  $request->remarks,
            'division_id'     =>  $request->division_id,
            'district_id'     =>  $request->district_id,
            'upazila_id'      =>  $request->upazila_id,
            'farmer_point_id' =>  $request->farmer_point_id,
            'user_type_id'    =>  3   // 3 is for farmer
        ]);
        $image = Image::make($request->profile_picture);
        $image->resize(250, 272);
        $image->save(public_path("uploads/Farmers/farmer_$farmer->id.jpg"));

        return redirect("farmer/{$farmer->id}");
    }
4

1 回答 1

0

理想的做法是先上传图像,然后将文件路径保存到数据库。

理想情况下,最好将您的上传逻辑提取到一个单独的独立类中。您可以使用以下内容作为指南。

<?php
Class UploadImage
{
 /**
     * UploadPostImage constructor.
     * .
     * @param UploadedFile $postedImage
     *
     */
    public function __construct(UploadedFile $postedImage)
    {
        $this->postedImage = $postedImage;
    }

 /**
     * Create the filename
     *
     */
    public function getFilename()
    {
        $dt = Carbon::now();
        $timestamp = $dt->getTimestamp();

        $this->filename = $timestamp . '_' . $this->postedImage->getClientOriginalName();
    }

 /**
     * Create the image and return the path
     *
     * @param $path
     * @param int $width
     * @return mixed
     */
    public function createImage($path, $width = 400)
    {
        // Upload the image
        $image = Image::make($this->postedImage)
            ->resize(250, 272);

        $image->save(public_path($path . $this->filename, 60));

        return $path . $this->filename;
    }
}

在您的控制器中,您可以调用此类

$uploadImage = new Image(UploadedFile $file);
$uploadImage->getFilename();
$data['image'] = uploadImage->createImage('your-upload-path');

// 将其他数据添加到 $data 数组中,然后保存到数据库。

 $data['phone'] = $request->name,
    $data['address'] = $request->address
    // Add other data then pass it into User::create()

当您在控制器中调用 createImage() 时,路径会返回给您,您可以将其保存在数据库中。我希望这有帮助!

于 2016-09-19T21:09:13.423 回答