Laravel用户发布图片

时间:2018-02-21 09:52:14

标签: image laravel post upload

这是在用户控制器

  public function store(Request $request, User $user)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'body' => 'required'
        ]);


        if( $request->hasFile('image') ) {
            $image = $request->file('image');
            $filename = time() . '.' . $image->getClientOriginalExtension();

            Image::make($image)->resize(600, 600)->save( public_path('uploads/images/' . $filename ) );
        }

        $post = Post::get();
        $post->image = $filename;
        $post->save();

         Session::flash( 'sucess', 'Post published.' );

        auth()->user()->publish(
            new Post(request(['body']))
        );

        return redirect('/');
    }

我无法发布图片,看到一些备用错误SQLSTATE [HY000]:常规错误:

  

1364字段'image'没有默认值(SQL:insert into   postsbodyupdated_atcreated_at)值(dddd,2018-02-21   09:42:49,2018-02-21 09:42:49))

2 个答案:

答案 0 :(得分:1)

那是因为$ image为null并且它在DB中的列不可为空,使其可以为空

$table->string('image')->nullable();

或不传递null

$post->image = $filename ?? '';//this is php 7 syntax

 $post->image = isset($filename) ? $filename :' ';

答案 1 :(得分:0)

由于该字段不可为空,因此您应将代码更改为:

$post->image = $filename ?? '';

或者在相关的迁移文件中创建image字段nullable

$table->string('image')->nullable();

此外,而不是get()

$post = Post::get();

您应该只创建一个新的Post实例:

$post = new Post;