【问题标题】:Laravel User Post ImageLaravel 用户发布图片
【发布时间】:2018-07-31 20:24:58
【问题描述】:

这是在用户控制器中

  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 字段“图像”没有默认值(SQL:插入 posts (body, updated_at, created_at) 值 (dddd, 2018-02-21 2018-02-21 09:42:49 09:42:49))

【问题讨论】:

  • dd($filename) 它可能为空;
  • 你能展示你的publish方法吗?
  • public function publish(Post $post) { $this->posts()->save($post); }
  • 仍然有同样的错误

标签: image laravel post upload


【解决方案1】:

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

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

或者不传null

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

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

【讨论】:

    【解决方案2】:

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

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

    或者在相关迁移文件中设置image字段nullable

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

    另外,代替get():

    $post = Post::get();
    

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

    $post = new Post;
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 2019-12-29
      • 1970-01-01
      • 2015-06-25
      • 2016-06-08
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多