laravel image upload error - php

i'm using intervention package to upload images with laravel and all things are fine from creating to saving image but the problem in the image column in database it stores this name with path
/private/var/folders/18/0w78rt691m99y_kv8xln4n0c0000gn/T/phpFkP3Gh
this is my code:
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
\Image::make($image)->save($location);
}
and this is the image name stored in images file 1503847676.jpg
please help me to find, where is the problem?
this is my whole method
public function update(Request $request, $id)
{
// Validating fields requests
$this->validate($request, [
'title' => 'required|min:6',
'subtitle' => 'required|min:6',
'slug' => 'required',
'body' => 'required',
'image' => 'required|mimes:jpeg,png,jpg,gif,svg'
]);
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
\Image::make($image)->save($location);
}
//find target post
$post = Post::find($id);
//create upadeted data from inputs fields
$post->title = $request->title;
$post->subtitle = $request->subtitle;
$post->image = $filename;
$post->slug = $request->slug;
$post->image = $request->image;
$post->status = $request->status;
$post->body = $request->body;
//save the new data to database
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
return redirect('/admin/post');
}

You don't need Intervention package for simple image upload w/o any modifications like resize etc. Try this
if( $request->hasFile('image')) {
$image = $request->file('image');
$location = public_path(). '/images/';
$filename = time() . '.' . $image->getClientOriginalExtension();
$image->move($location, $filename);
}
//find target post
$post = Post::find($id);
$post->image = $filename;
//remaining code
$post->save();

You can try this if you use Intervention image
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalName();
$path = public_path('images/' . $filename);
Image::make($image->getRealPath())->save($path);
$post->image = 'images/' . $filename;

I had a similar error like yours, I solved it by using the following:
$file = Input::file('image');
$image->move($location, $file->getClientOriginalName());

Related

Having trouble using intervention/image in laravel-9

I tried to resize my image before uploading but is not working but I am able to upload the image, Here is my Controller:
public function store(Request $request)
{
$validatedData = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:20480',
]);
$imageFile = $request->file('image');
$name = $imageFile->getClientOriginalName();
$path = $request->file('image')->store('images', 'public');
$resize = Image::make($imageFile)->resize(50, 50)->stream();
$save = new Gallery;
$save->image = $path;
$save->status = 1;
$save->user_id = Auth::id();
$save->save();
return redirect('gallery')->with('success', 'Image has been uploaded')->with('image',$name);
}
try below example source code. I have done image resize functionality in one of my project with Laravel version 8
<?php
if($request->hasFile('dealimg')){
$file = $request->File('dealimg');
$original_name = $file->getClientOriginalName();
$file_ext = $file->getClientOriginalExtension();
$destinationPath = 'uploads/deals';
$file_name = "deal".time().uniqid().".".$file_ext;
// $path = $request->deal_img->store('uploads');
$resize_image = Image::make($file->getRealPath()); //for Resize the Image
$resize_image->resize(150, 150, function($constraint){ //resize with 150 x 150 ratio
$constraint->aspectRatio();
})->save(public_path($destinationPath) . '/' . $file_name);
$deal_img = $destinationPath."/".$file_name;
$request->request->add(['deal_img' => $deal_img]);
}
?>
I hope this one helps to you... see this

Failed to rename image and upload using storeAs in Laravel

I created a form to store article with an image , and generate a resized version as thumbnail from it.
I want the image to be renamed after the article slug and stored in the "public/img/articles-images " directory but i keep receiving : "Image source not readable" error
This is the image upload handler function in my controller :
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug;
$successUploaded = $image->storeAs('img/articles-images', $fileName);
if($successUploaded) {
$width = config('cms.image.thumbnail.width');
$height = config('cms.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make('img/articles-images' . '/' . $fileName)
->resize($width, $height)
->save('img/articles-images' . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}
storeAs() method, which receives the path, the file name, and the (optional) disk as its arguments :
$successUploaded = $request->file('image')->storeAs(
'images', $fileName
);
I solved it ! Apparently there was no need to storeAs() method at all , the new code is like below :
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug.'.' .$image->getClientOriginalExtension();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
// //

How to get the id from another post form when using a multiple image uploader using laravel?

I have two forms the blog post and multiple image uploader, basically I want to use multiple image uploader in the blog post form, however I need to get the ID from blog post form so each blog posts has it's own unique set of images. I am aware you can use foreign keys to establish the link between the two tables but I am unsure how to do this. Right now the blog post form only does a single file upload so I want a way to use the multiple image uploader logic into the PostController which then saves into the images table. Really appreciate the help thank you.
ImagesController
public function store(Request $request)
{
if(!$this->validate($request, [
'id' => 'integer',
'images.*' => 'sometimes|image|nullable|mimes:jpeg,png,jpg,gif,svg,webp|max:25000',
'post_id' => 'required'
])) {
return redirect()->back()->with('errors');
}
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/image', $fileNameToStore);
$image = new Images;
$image->images = $fileNameToStore;
$image->post_id = $request->post_id;
$image->save();
}
}
return back()->with('Images have been uploaded!');
}
PostController
public function store(Request $request)
{
// Validate posted form data
$validated = $request->validate([
'id' => 'integer',
'vehicle' => 'required|string',
'h1' => 'required|string',
'page_title' => 'required|string',
'meta_description' => 'required|string',
'image' => 'sometimes|image|nullable|max:5000',
'content' => 'required|string',
'active' => 'integer',
'user_id' => 'required'
]);
// Create slug from title
$validated['slug'] = Str::slug($validated['vehicle'], '-');
$validated['active'] = isset($request->active[0]) ? 1 : 0;
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/image', $fileNameToStore);
}else {
$fileNameToStore = null;
}
// Create and save post with validated data
$post = new Post;
$post->id = $request->input('id');
$post->vehicle = $request->input('vehicle');
$post->slug = $request->input('slug');
$post->h1 = $request->input('h1');
$post->page_title = $request->input('page_title');
$post->meta_description = $request->input('meta_description');
$post->image = $fileNameToStore;
$post->content = $request->input('content');
$post->active = $validated['active'];
$post->user_id = $request->input('user_id');
$post->slug = $validated['slug'];
$post->save();
// Redirect the user to the created post with a success notification
return redirect(route('admin.posts.show', $post))->with('notification', 'Post created!');
}
You can store images in your PostController.
Remove this part in your PostController (in store() method):
if($request->hasFile('image'))
{
$filenameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $request->file('image')->storeAs('public/image', $fileNameToStore);
}else {
$fileNameToStore = null;
}
And after creating the post put the loop to save images. Change this line:
$image->post_id = $request->post_id;
to this:
$image->post_id = $post->id;
First use the Images model at the top of the PostController. Your new loop should looks like this:
if($request->hasfile('images'))
{
foreach($request->file('images') as $image)
{
$filenameWithExt = $image->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extension;
$path = $image->storeAs('public/image', $fileNameToStore);
$image = new Images;
$image->images = $fileNameToStore;
$image->post_id = $post->id;
$image->save();
}
}
Then (based on relationships in your models) you can access the image with something like this:
#foreach($post->images as $image)
<img src="public/image{{ $image->fileNameToStore">
#endforeach

Error = Method Illuminate\Http\UploadedFile::save does not exist

I can't add images to the database. I am always getting this error.
$this->validate($request, [
'imageName' => 'required',
'imagePath' => 'required',
]);
$image->productId = $request->input('productId');
$image->imageName = $request->input('imageName');
if (request()->hasFile('imagePath')){
$image = $request->file('imagePath');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/productImages/');
$image->move($destinationPath, $imageName);
$image->imagePath = $destinationPath . $imageName;
}
$image->imageCode = $request->input('imageCode');
$image->save(); // error line
return redirect()->route('image.index');
Thank you for your help
Actually from your code what I can understand is that you have an eloquent object and you want to upload an image and save the image data to eloquent object,
but inside your if (request()->hasFile('imagePath')){ } you have overwritten your $image variable :)
In that case change your code inside if conditional to the following
if (request()->hasFile('imagePath')){
$uploadedImage = $request->file('imagePath');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/productImages/');
$uploadedImage->move($destinationPath, $imageName);
$image->imagePath = $destinationPath . $imageName;
}

Update image from edit form Laravel

I want to edit the the blog form in Laravel. All other text information like Title, Body are successfully edited. But Image could not be updated. New image is not uploaded and image path is set as C:\xampp\tmp\php2030.tmp.
My Controller for edit.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$post->update($requestData);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
$image = '/images/'.$fileNameToStore;
$post->save();
}
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
What is wrong with it?
When PHP receives a file upload, by default it writes it to a temporary directory like you're getting, and automatically deletes the file after the request has been handled.
What you need to do is move the uploaded file to a safe location.
Laravel 5.5 has a store method for file uploads that might be of interest.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
// UPDATE TEMPORARY IMAGE PATH WITH ACTUAL PATH
$requestData['image'] = "/media/{$fileNameToStore}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Please, use the code below:
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$pathToStore = public_path('media');
if ($request->hasFile('image'))
{
$file = $request->file('image');
$rules = array('file' => 'required|mimes:png,gif,jpeg'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$filename = $file->getClientOriginalName();
$extension = $file -> getClientOriginalExtension();
$picture = sha1($filename . time()) . '.' . $extension;
$upload_success = $file->move($pathToStore, $picture);
if($upload_success)
{
//if success, create thumb
$image = Image::make(sprintf($pathToStore.'/%s', $picture))->resize(600, 531)->save($pathToStore.'/thumb/'.$picture);
}
}
$requestData['image'] = "$pathToStore/{$picture}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}

Categories