-2

我正在尝试为用户创建文件上传选项。我有一个用户表,我创建了一个新的“文档”表并添加了 user_id 作为外键。

当我尝试上传文件时,出现此错误:

“SQLSTATE[HY000]:一般错误:1364 字段‘user_id’没有默认值(SQL:插入documents( 、、、、、 )值(我的文档title, doc.pdf file,6c229500-7430-11ea-92c8-05ffc2487316 , 2020-04-01 15:49:50, 2020-04-01 15:49:50))"uuidupdated_atcreated_at

这是我的商店功能:

public function store(Request $request)
    {
        $document = $request->all();
        $document['user_id'] = User::where('id',auth()->user()->id)->first();
        $document['uuid'] = (string)Uuid::generate();
        if ($request->hasFile('file')) {
            $document['file'] = $request->file->getClientOriginalName();
            $request->file->storeAs('documents', $document['file']);
        }
        Document::create($document);
        return redirect()->route('documents.index');
    }

这是表格:

                        <form action="{{ route('documents.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf

                        Title:
                        <br>
                        <input type="text" name="title" class="form-control">

                        <br>

                        File:
                        <br>
                        <input type="file" name="file">

                        <br><br>

                        <input type="submit" value=" Upload document " class="btn btn-primary">

                    </form>

知道如何解决这个问题吗?

4

1 回答 1

2

Use Auth;
public function store(Request $request)
    {
        $document = $request->all();
        $document['user_id'] = Auth::user()->id;
        $document['uuid'] = (string)Uuid::generate();
        if ($request->hasFile('file')) {
            $document['file'] = $request->file->getClientOriginalName();
            $request->file->storeAs('documents', $document['file']);
        }
        Document::create($document);
        return redirect()->route('documents.index');
    }

于 2020-04-01T15:58:51.927 回答