Laravel 5图片上传问题

时间:2015-09-29 17:58:43

标签: php laravel

我是laravel的新手并使用laravel5。 这是我的控制器:

public function store(Request $request)
{
    $image=$request->all();
    if($request->hasFile('image')) {
        $file = $request->file('image');
        $name = $file->getClientOriginalName();
        $image->filePath = $name;
        $file->move(public_path().'/images/', $name);
        Image::create($image);
    }      
    return redirect()->back();
}

这是我的表格:

{!! Form::text('title') !!}
{!! Form::text('description')!!}
{!! Form::file('image') !!}
{!! Form::submit('Save') !!}

在上传时获取错误“尝试分配非对象的属性”。提前致谢

3 个答案:

答案 0 :(得分:0)

将您的代码更改为以下内容:

public function store(Request $request)
{
    $image=$request->all();
    if($request->hasFile('image')) {
        $file = $request->file('image');
        $name = $file->getClientOriginalName();
        $image['image'] = $name; // This line has changed
        $file->move(public_path().'/images/', $name);
        Image::create($image);
    }      
    return redirect()->back();
}

答案 1 :(得分:0)

它应该是这样的:

public function store(Request $request) {
    $image=$request->all();
    if($request->hasFile('image')) {
        $file = $request->file('image');
        $name = $file->getClientOriginalName();
        $image['image'] = $name;
        $file->move(base_path().'/images/', $name);    
    }      
    Image::create($image);
    return redirect()->back();
}

答案 2 :(得分:0)

问题是 $ image 请求即时之一。而且您正在尝试获取一个不存在的请求对象表单。

您需要对代码进行一些更改,这应该适合您

public function store(Request $request)
{
    $image = $request->all();

    if($request->hasFile('image')) {
        $file = $request->file('image');

        //you also need to keep file extension as well
        $name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();

        //using array instead of object
        $image['filePath'] = $name;
        $file->move(public_path().'/images/', $name);

        Image::create($image);

    }      
    return redirect()->back();
}