-2

I am trying to create a file upload option for the user. I have a users table and I created a new 'documents' table and added user_id as foreign key.

When I try to upload a file I get this error:

"SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into documents (title, file, uuid, updated_at, created_at) values (my document, doc.pdf, 6c229500-7430-11ea-92c8-05ffc2487316, 2020-04-01 15:49:50, 2020-04-01 15:49:50))"

This is my store function:

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');
    }

This is the form:

                        <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>

Any idea how to fix this?

andrea
  • 39
  • 2
  • 8

1 Answers1

3

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');
    }
sd077
  • 465
  • 1
  • 7
  • 25