Update in one to one relation table laravel

2.2k views Asked by At

I have 2 tables that are in one to one relationship:

tours :

id|title|content

featured_image:

id|tour_id|name|path

My models FeaturedImage.php:

class FeaturedImage extends Model
{
protected $fillables = [
    'name',
    'path',
    'tour_id',
];

public function tour()
 {
  return $this->belongsTo('App\Tour');
 }
}

Tours.php

class Tour extends Model
{
protected $fillables = [
    'title',
    'content',
];

public function featuredImage()
 {
  return $this->hasOne('App\FeaturedImage');
 }
}

I'm trying to update the featured_image table when new image for tour is uploaded:

  1. update path column in featured_image table with new file's path
  2. Delete the old image

Below is my method for updating featured_image's path column:

// update featured image       
    if ($request->hasFile('featured_image')) {
    $featured_image= new FeaturedImage;
// add the new photo
    $image = $request->file('featured_image');
    $filename = $image->getClientOriginalName();
    $location = 'images/featured_image/'.$filename; 
    //dd($location);
    Image::make($image)->resize(800, 400)->save($location);

    $oldFilename= $tour->featuredImage->path;
// update the database
    $featured_image->path = $location;
// Delete the old photo
    File::delete(public_path($oldFilename));
    }

The above code sucessfully deletes the old image and uploads the new, but it fails to update the path column. I ran dd($location);, it gives the path of the new image but doesn;t save in the db column.

1

There are 1 answers

1
Alexey Mezenin On BEST ANSWER

You should save relation like this:

$featuredImage = $tour->featuredImage;
$featuredImage->path = $location;
$tour->featuredImage()->save($featuredImage);

https://laravel.com/docs/5.3/eloquent-relationships#the-save-method