0
votes

I have created the following 4 model and its table structure for my project:

Media.php To upload images in app

Medias table structure

id | path

Example of path:uploads/images/media/food-1542110154.jpg

Post.php Create post

Posts table structure

id | title | content

FeaturedImage.php Featured image for post

Posts table structure

id | post_id| path

Post model and FeaturedImage model are in a one-to-one relationship

UploadImage.php To resize the uploaded image and move it to another directory. This model doesn't have migration and controller

Code snippet from PostsController.php to create the post

use App\UploadImage;
use App\Media;
class PostController extends Controller
{
private $imagePath= "uploads/images/post/";
public function store(Request $request)
{
    $post = new Post;
    $post->title = $request->title;
    $post->content = $request->content;
    $post->save();

    $media = Media::find($request->featured);
    if (!File::exists($this->imagePath)) {
        File::makeDirectory($this->imagePath);
    }
    $upload = new UploadImage;
    $image= $upload->uploadSingle($this->banner, $media->path, 400,300);
    $post->image()->save(new FeaturedImage([
        'path' => $image
    ]));

}
  Session::flash('success', 'Post created sucessfully !');
  return redirect()->route('post.index');
}

Code snippet from UploadImage.php

use Intervention\Image\Facades\Image;
use Spatie\LaravelImageOptimizer\Facades\ImageOptimizer;
use Illuminate\Database\Eloquent\Model;
class UploadImage extends Model
{

  public  function  uploadSingle($savePath, $image,$width,$height)
 {
    Image::make(public_path($image))->fit($width, $height)->save($savePath);
    ImageOptimizer::optimize($savePath);
    return $savePath;
 }  
}

In my Laravel app, I'm trying to edit dimension of the already uploaded image with method written in UploadImage.php and save edited image in post directory and save its path in featured_images table.

But I've been getting **Can't to write image data to path ** error.

I would be very thankful if anyone could point out the mistakes that I've made.

Please do not mark this as duplicate content. As I've been gone through almost all posts related to this kind of error and they have been no help to me.

1
forget about my previous comment, what is $media->path? Shouldn't it be $this->imagePath ? - Taha Paksu
public_path to save the images ? usually we use storage_path ... public path is http's user writable ? - simonecosci
@TahaPaksu $media->path is the path of original image that has been alreadey uploaded. - psudo

1 Answers

0
votes

Tweaked few lines in my UploadImage.php model and got it solved.

public  function  uploadSingle($savePath, $image,$width,$height)
{
    $filename = basename($image);
    $location = $savePath . $filename;
    Image::make($image)->save($location);
    ImageOptimizer::optimize($location);
    return $location;
}