rubol's avatar
Level 2

Can't write image data to path [Can't write image data to path ] Image Intervention

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->mediaId); //mediaId is from dropdown in create view
    if (!File::exists($this->imagePath)) {
        File::makeDirectory($this->imagePath,0775,true);
    }
    $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.

0 likes
2 replies
rubol's avatar
rubol
OP
Best Answer
Level 2

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;
    } 

Please or to participate in this conversation.