如何使用laravel将图片上传到databae?

时间:2020-02-25 12:05:09

标签: laravel

我正在尝试将图像上传到数据库中,但是很遗憾,没有将图像插入数据库中如何解决该问题,谢谢您。

数据库表 https://ibb.co/3sT7C2N

控制器

public function Add_slider(Request $request)
{
    $this->validate($request, [
        'select_image'  => 'required'
    ]);

    $content = new Sliders;

    if($request->file('select_image')) {
        $content->slider_image = Storage::disk('')->putFile('slider', $request->select_image);
    }

    $check = Sliders::create(
        $request->only(['slider_image' => $content])
    );

    return back()
    ->with('success', 'Image Uploaded Successfully')
    ->with('path', $check);
}

2 个答案:

答案 0 :(得分:1)

您应该采用以下方式:

public function Add_slider(Request $request)
{
     $this->validate($request, [
         'select_image'  => 'required'
     ]);
     $image = $request->file('select_image');         
     $extension = $image->getClientOriginalExtension();
     Storage::disk('public')->put($image->getFilename().'.'.$extension,  File::get($image));
     $content = new Sliders;
     if($request->file('select_image'))
     {
         $content->slider_image = $image->getFilename().'.'.$extension;;
         $content->save();         

         $check = Sliders::where('id', $content->id)->select('slider_image')->get();
         return back()->with('success', 'Image Uploaded Successfully')->with('path',$check);
     }
}

在视图刀片文件中:

<img src="{{url($path[0]->slider_image)}}" alt="{{$path[0]->slider_image}}">

答案 1 :(得分:0)

这仅返回文件名:

Storage::disk('')->putFile('slider', $request->select_image);

改为使用此:

Sliders::create([
    'slider_image' => $request->file('select_image')->get(),
]);

确保数据库中的列类型为二进制/ blob。