Home > other >  why i can't update image in table using laravel and angular?
why i can't update image in table using laravel and angular?

Time:09-05

I have a cvs table, which contains image, I want to update this image, use laravel and angular, but it doesn't work. my cvs table contains just an image field. I believe that angular just sends a string like: http://localhost/editimage/public/storage/annonces\\September2022\\064914000201058_896x598_c.jpg", and laravel considered image as a string is not correct an image upload, and for that laravel considered the condition if($request->hasFile('image')) is false then it does not enter the condition and it gives me array null.

editimage.component.html

<div >
  <form (ngSubmit)="editimage()">    
    <label>image<span >*</span></label>

    <input type="file"  name="image" [(ngModel)]="image.image" #image="ngModel" (change)="fileEvent($event)"/>

    <div >
      <img [src]="image.photo" style="width: 240px;height: 240px">
    </div>
    {{ image | json }}

    <button  type="submit" >Modifier Annonce</button>
  </form>
  </div> 

editimage.component.ts

  constructor(private http:HttpClient,private route:ActivatedRoute) { }
  image:any={
    id:0,
    photo:''
  };
  id:number = 0;

  ngOnInit(): void {
    this.id = this.route.snapshot.params['id']; 
    this.getImage();
  }

    editimage(){
      this.http.put('http://localhost/editimage/public/api/cvs/' this.image.id,this.image).subscribe(image => {
          console.log(image);
      }) 
      } 

ImageController.php

 public function update(Request $request, $id)
        {
            $cv = Cv::where('id',$id)->first();
            if($request->hasFile('image'))
           {
            $image = date('His').$request->file('image')->getClientOriginalName();
            $path = "public\\annonces\\".$jdate->format('F').$jdate->year;
            $pathh = "annonces\\".$jdate->format('F').$jdate->year."\\".$image;
            $move = $request->file('image')->storeAs($path,$image);
            $request->image= $pathh;
            $cv->image = $request->image;
            }
    
            $cv->save();
            return $cv;
        }

routes/api.php

Route::resource('cvs','CvsController');

CodePudding user response:

I guess that's because You check an input with name photo but upload input name image

CodePudding user response:

You are probably using a PUT or PATCH request right? In that case, in order to Laravel be aware of request content, you need to use a POST request and add '_method': 'PATCH' in your payload from your client side. Not sure how postman handles it, but you should use formData or multipart/form-data for uploading files.

  • Related