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:
- update
path
column infeatured_image
table with new file's path - 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.
You should save relation like this:
https://laravel.com/docs/5.3/eloquent-relationships#the-save-method