重命名图像,然后将图像名称保存到数据库中

时间:2016-01-12 11:11:10

标签: php laravel-5.2 intervention

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

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}");
    }

1 个答案:

答案 0 :(得分: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()时,路径将返回给您,您可以将其保存在数据库中。 我希望这有帮助!