Laravel is unable to read formdata

Viewed 2528

I am making a web app, using angular on the frontend and laravel on the backend. But I am getting some issues when I am trying to upload some data to the laravel API.

I am using on Angular the formdata, because I need it for upload files. But when I send the data to Laravel, it does not pass the validation, because Laravel is getting empty data.

This is the function that is called on submit.

  onUpload() {
    const fd = new FormData;
    fd.append('video', this.video);
    fd.append('image', this.image);
    fd.append('title', 'Hello world');
    fd.append('description', 'Hello world');
    fd.append('userId', '1');
    fd.append('categoryId', '1');

    const headers = new HttpHeaders({
      'Content-Type': 'application/json'
    });

    this.http.post('here goes the real url', fd, {
      headers: headers
    }).subscribe(event => {
        console.log(event);
    });
  }

And this is my validator on Laravel.

    public function rules(){
        $datos = $this->validationData();
        return [
            "description" => ["max:2000"],
            "video" => ["required", "mimes:mp4,mov,ogg"],
            "image" => ["required", "image", "mimes:jpg,jpeg,png,gif,webp"],
            "title" => ["required","min:4", "max:100"],
            "userId" => ["required", "numeric"],
            "categoryId" =>["numeric"]
        ];
    }

And also, this is the error message:

errors:
image: ["The image field is required."]
title: ["The title field is required."]
video: ["The video field is required."]
userId: ["The user id field is required."]
__proto__: Object
message: "The given data was invalid."

I need something extra on Laravel to read the data? Or I am uploading wrong? Thanks you a lot for your time.

2 Answers

try changing Content-type to multipart/form-data

const headers = new HttpHeaders({
      'Content-Type': 'multipart/form-data'
});

Delete 'Content-Type': '...' from headers. works for me:

my code was: importFile(unit_id, data): Observable { let headers = new HttpHeaders().set('Content-Type', 'multipart/form-data').set('x-access-token', this.token); return this.http.post(this.api + /unit/${unit_id}/import, data, {reportProgress: true, observe: 'events', headers:headers}).pipe(); }

and now: importFile(unit_id, data): Observable { let headers = new HttpHeaders().set('x-access-token', this.token); return this.http.post(this.api + /unit/${unit_id}/import, data, {reportProgress: true, observe: 'events', headers:headers}).pipe(); }

Related