【问题标题】:Laravel sql table error when i try to upload当我尝试上传时 Laravel sql 表错误
【发布时间】:2020-04-05 09:03:00
【问题描述】:

这是我得到的错误

SQLSTATE[HY000]:一般错误:1 表帖子没有名为标题的列(SQL:插入“posts”(“caption”、“image”、“user_id”、“updated_at”、“created_at”)值(标题,

为什么会这样

张贴表代码

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('caption');
        $table->string('image');
        $table->timestamps();

        $table->index('user_id');

blade.php 代码

<input id="caption" 
                                type="text" 
                                class="form-control @error('caption') is-invalid @enderror" 
                                name="caption"
                                value="{{ old('caption') }}" 
                                autocomplete="caption" autofocus>

我有我的 PostsController.php

public function store()
    {
        $data = request()->validate([
            'caption' => 'required',
            'image' => ['required', 'image'],
        ]);

        auth()->user()->posts()->create($data);    


        dd(request()->all());
    }

为什么会出现错误?

【问题讨论】:

    标签: php sql laravel


    【解决方案1】:

    当您尝试将数据存储到 post 表中时,您可以执行以下简单操作:

    $data = request()->validate([
        'caption' => 'required',
        'image' => ['required', 'image']        
    ]);
    
    $data['user_id'] = Auth::id();
    
    $post = Post::create($data);
    

    另外,您需要导入 Post 模型以将数据插入到 post 表中,如下所示:

    namespace App\Http\Controllers;
    
    use App\Post;
    

    【讨论】:

    • 是的,当我这样改变时,我得到的错误是 Class 'App\Http\Controllers\Post' not found
    • 为此您需要导入 Post 模型。为此添加使用 App\Post;控制器顶部的行。
    • @NutellaCrumpy 我已经更新了我的答案。调查一下。
    • @NutellaCrumpy 很高兴为您提供帮助,如果此答案解决了您的问题,请通过单击答案旁边的复选标记将其标记为已接受并投票。
    猜你喜欢
    • 2017-01-25
    • 2011-06-02
    • 1970-01-01
    • 2019-09-26
    • 2020-10-06
    • 2018-08-31
    • 2020-10-01
    • 1970-01-01
    • 2020-12-16
    相关资源
    最近更新 更多