SQLSTATE[23502]: Not null violation: 7 Laravel API error

Viewed 281

Below is an API to upload files, and it displays the following error.

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "Userid" of relation "files" violates not-null constraint\nDETAIL: Failing row contains (7, null, Distance Learning Promo.mp4, null, null, null, 2021-07-07 13:38:07, 2021-07-07 13:38:07). (SQL: insert into "files" ("FileName", "updated_at", "created_at") values (Distance Learning Promo.mp4, 2021-07-07 13:38:07, 2021-07-07 13:38:07) returning "id")

Also, Postman shows the status 500 internal status error. I don't think my Userid column here is null. Even if Userid column is inserted a dummy value like this: $dataToInsert['Userid'] =1. Also, it shows the same error.

Controller

class UploadController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function upload(Request $request)
    {
        $file = $request->file('file_name');
        $fileName = $file->getClientOriginalName();
        $folder = uniqid() . '-' . now()->timestamp;
        $file->storeAs('public/other-document/' . $folder, $fileName);

        $filePath = $folder . '/' . $fileName;
        $dataToInsert = array();
        $dataToInsert['FileName'] = $fileName;
        $dataToInsert['FilePath'] = $filePath;
        if ($request->has('uploadType')) {
            $dataToInsert['FileType'] = $request->uploadType;
        }
        $dataToInsert['uploadedBy'] = Auth::user()->id;
        $dataToInsert['Userid'] = $request->bearerToken();
        Uploads::create($dataToInsert);
    }
}

Migration

Schema::create('files', function (Blueprint $table) {
    $table->id();
    $table->string('Userid');
    $table->string('FileName');
    $table->string('FilePath');
    $table->string('FileType');
    $table->integer('uploadedBy');
    $table->timestamps();
});
1 Answers

I am so sorry. I can't write comments yet. But did you add fields to Model fillable array? I had a similar problem. And that was because i didn't add that field to fillable array of Model.

Related