Laravel 5.1 $ request->文件返回null

时间:2018-07-23 16:45:49

标签: laravel laravel-5.1

我目前正在使用一种简单的表单来允许用户上传名称和图像。不幸的是,$ request-> input('image')和Input :: file('image')返回null。如果我执行$ request-> string('image'),则返回上传文件的名称。有人可以向我解释我在做什么错吗?

表格

{!! Form::open(['url' => 'categories']) !!}
    <div class="form-group">
        {!! Form::label('name', 'Naam') !!}
        {!! Form::text('name') !!}
    </div>
    <div class="form-group">
        {!! Form::file('image', null) !!}
    </div>
    {!! Form::submit('Create Category!', array('class' => 'btn btn-primary')) !!}
{!! Form::close() !!}

控制器功能:

    public function store(Request $request)
    {
        $rules = [
            'name'       => 'required',
            'image'      => 'required'
        ];

        $validator = Validator::make(Input::all(), $rules);

        /**
        * Adding the code here also returns null../
        * 
        $file = $request->file('image');
        dd( $request->file('image'));
        * 
        */

        // process the login
        if ($validator->fails()) {
            return Redirect::to('categories/create')
                ->withErrors($validator)
                ->withInput(Input::except('password'));
        } else {

            $file = $request->file('image');
            dd( $request->file('image'));
            $destination = public_path() . '/img/';
            $name = Carbon::now()->toDateTimeString();
            $extension = $file->getClientOriginalExtension();
            $filename = $name . '.' . $extension;
            $file->move($destination, $filename);

            $category = new Category();
            $category->name       = Input::get('name');
            $category->file_path = $filename;
            $category->save();

            Session::flash('message', 'Successfully created Category!');
            return Redirect::to('categories');
        }

    }

1 个答案:

答案 0 :(得分:3)

正如注释中指出的那样,表单缺少enctype="multipart/form-data"属性。

要保持Form门面主题,您可以使用files静态方法将open键添加到数组中:

{!! Form::open(['url' => 'categories', 'files' => true]) !!}