I am adding the ability to edit an image that is already uploaded on a shopping cart app I am building. I am able to upload an image fine. I am also able to edit every field perfectly except for the image file upload.
I have tried using the same code I have in the upload function to basically upload another image over the existing one but it does not work and throws an error
Call to a member function getClientOriginalExtension() on a non-object
I am using the Laravel framework with intervention and went to the main site of intervention and it does not show an update or edit method. It just shows a delete method.
I need some help in figuring out how to update the image in my postEdit function.
I really have tried everything I know and have researched this with google and cannot figure this out.
My problem lies in this line of code:
File::update('public/'.$product->image);
Thank you for the right direction.
Here is the image upload function (which works perfect)
public function postCreate() {
$validator = Validator::make(Input::all(), Product::$rules);
if ($validator->passes()) {
$product = new Product;
$product->category_id = Input::get('category_id');
$product->title = Input::get('title');
$product->description = Input::get('description');
$product->price = Input::get('price');
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/products/' . $filename);
Image::make($image->getRealPath())->resize(468, 249)->save($path);
$product->image = 'img/products/'.$filename;
$product->save();
return Redirect::to('admin/products/index')
->with('message', 'Product Created');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong')
->withErrors($validator)
->withInput();
}
Here is the edit image upload function which I cannot get to work.
public function postEdit() {
$product = Product::find(Input::get('id'));
if ($product) {
File::update('public/'.$product->image);
$product->update(Input::all());
return Redirect::to('admin/products/index')
->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')
->with('message', 'Something went wrong, please try again');
}
First there is no method for the File facade called update.
You have to reprocess the image to update it.
Secondly, the error is being thrown from the upload. This could be because the image is not being sent through the form properly.
Make sure you have files attribute on your form open.
{{ Form::open(array('route'=> array('aroute'),'method' => 'post', 'files' => true)) }}
If your file is still not being sent check your php.ini setting as the file size of the image could be greater of that set in the post_max_size or upload_max_filesize to a value greater than that size.
Also the change the line;
$path = public_path('img/products/' . $filename);
to
$path = public_path() . 'img/products/' . $filename;
And to edit the image with intervention you need to save the file.
Use;
$image->move($path);
then you can do;
Image::make($path)->resize(468, 249)->save($path);
Related
The project works fine on my localhost but has issues on a live shared server.
I have tried adding this code to my index.php
// set the public path to this directory
$app->bind('path.public', function() {
return __DIR__;
});
I have tried adding this code in a new sym.php file in my public folder
<?php
$targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';
$linkFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage';
symlink($targetFolder,$linkFolder);
echo 'Symlink process successfully completed';
?>
I have tried adding this on my web.php and then running site/linkstorage
Route::get('/linkstorage', function () {
Artisan::call('storage:link');
});
None of these solutions works
here is a snippet of my Controllers code:
public function storeBrand(Request $request){
$this->validate($request, ['brand_name'=> 'required',
'brand_url'=> 'required',
'brand_image'=>'image|nullable|max:1999']);
if($request->hasFile('brand_image')){
//1 : get filename with ext
$fileNameWithExt = $request->file('brand_image')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('brand_image')->getClientOriginalExtension();
//4 : file name to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('brand_image')->storeAs('public/BrandImages', $fileNameToStore);
}
else{
$fileNameToStore ='noimage.jpg';
}
$brand=new Brand();
$brand->brand_name =$request->input('brand_name');
$brand->brand_url =$request->input('brand_url');
$brand->brand_image =$fileNameToStore;
$brand->save();
return redirect('/create_brand')->with('status', 'The '.$brand->brand_name.' Brand has been saved successfully. Create another one.');
Note
When an image is uploaded the path can be traced, but the image is not found, returns an empty image.
Thank you for your time and assistance.
I have got the solution:
I Wrote down this code in my web.php route file:
Route::get('/linkstorage', function () { $targetFolder = base_path().'/storage/app/public'; $linkFolder = $_SERVER['DOCUMENT_ROOT'].'/storage'; symlink($targetFolder, $linkFolder); });
After that I navigated to my url/linkstorage
It worked!!
Looking at the code in your controller, it seems correct. Perhaps the error is within your form in the Blade file associated with this method. Based on experience I tend to forget to write this and this could probably sort out your error.
Write this on the form tag.
<form action="{{ insert the route here }}" method="POST" enctype="multipart/form-data">
// insert form input fields here...
</form>
I receive all user activities for each image upload they make, but I also want to receive the image in this foreach along with the table.
In my database I have 5 columns within the users table, which are doc1 doc2 doc3 doc4 and doc5. As I receive the image made by them together with the correct description, without having to log in to each user account
in fact there are 5 controllers of these, please don't notice the mess ^^ I'm new to programming
public function mudar_doc1(Request $request) {
// getting all of the post data
$file = array('image' => Input::file('image'));
// setting up rules
$rules = array('image' => 'required|image',); //mimes:jpeg,bmp,png and for max size max:10000
// doing the validation, passing post data, rules and the messages
$validator = Validator::make($file, $rules);
if ($validator->fails()) {
// send back to the page with the input data and errors
return Redirect::to('userp')->withInput()->withErrors($validator);
} else {
// checking file is valid.
if (Input::file('image')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
$extensoes = array("png", "jpeg", "jpg", "gif");
$resVal = in_array($extension, $extensoes);
if ($resVal) {
} else {
Session::flash('error', 'O upload não foi realizado com sucesso.');
return Redirect::to('userp');
}
$fileName = rand(11111, 99999) . '.' . $extension; // renameing image
Input::file('image')->move($destinationPath, $fileName); // uploading file to given path
$doc1 = asset($destinationPath . '/' . $fileName);
User::where('id', \Auth::user()->id)->update(['doc1' => $doc1]);
// sending back with message
Session::flash('success', 'ID Card Front Successfully Added!');
\App\RegistroAtividade::addAtividade('Cartao ID Frente');
return Redirect::to('userp');
} else {
// sending back with error message.
Session::flash('error', 'O upload não foi realizado com sucesso.');
return Redirect::to('userp');
}
}
}
<tbody>
#foreach($allAtividades as $atividade)
<tr>
<td>{{$atividade['id']}}</td>
<td>{{$atividade->getUser()->name}}</td>
<td>{{$atividade['ip']}}</td>
<td>{{$atividade['description']}}</td>
<td>{{$atividade['created_at']}}</td>
</tr>
</tbody>
#endforeach
I don't see much reference in your code for the Image / controller / view or data, please update your question and i will update this answer along
Some important note I would like to make
I would suggest you spare some time reading about the Eloquent Relations
Then you can create the Actividade Eloquent if you don't have it already
In Actividade Eloquent you can assign a user relations like so
Class Actividade {
//...
public function user(){
return $this->belongsTo(App\User::class, 'user_id');
}
}
The user method here will return the user by using the user_id column in the actividade table [if you have it set up correctly already], that will make it easier to fetch the user for activities $actividade->user->name, instead of $actividade->getUser()->name;
following this approach you can have an ImagesEloquent class having activities method which is relational just like activities having users and users having activities:
using this approach (skeleton) would be as easy as this:
#foreach(Image::find(1)->activities as $_activity){
<td><img src="{{Image::find(1)->filename}}"/></td> <!-- just an example here -->
<td>{{$_activity->id}}</td>
<td>{{$_activity->user->name}}</td>
<td>{{$_activity->ip}}</td>
<td>{{$_activity->description}}</td>
<td>{{$_activity->created_at}}</td>
#endforeach
You fetch the Image, you can fetch it's activities, and then each activity has users
It will take a bit of time (an hour or so) to learn about this, but will save you hundreds of hours in the future and get you a way cleaner code, i thought to suggest that.
I am trying to upload an image into my database. When i do upload, i get this error below
Call to undefined method Intervention\Image\ImageManager::upload()
Searching on the internet for solutions, i found this method
adding this line 'Intervention\Image\ImageServiceProvider' in my $providers in config/app.php
adding this line 'Image' => 'Intervention\Image\Facades\Image' in my $aliases in config/app.php
In my controller as well, i have use Image. But then i am still getting this error above. What could i be missing please?
Controller
public function uploadImagePost(UploadUserImageRequest $request)
{
$user = Auth::user();
$image = $request->file('profile_image');
if (false === empty($user->image_path)) {
$user->image_path->destroy();
}
$relativePath = 'uploads/users/' . $user->id;
$path = $relativePath;
$dbPath = $relativePath . DIRECTORY_SEPARATOR . $image->getClientOriginalName();
$this->directory(public_path($relativePath));
Img::upload($image, $path);
$user->update(['image_path' => $dbPath]);
return redirect()->route('my-account.home')
->with('notificationText', 'User Profile Image Uploaded successfully!!');
}
Library you have used doesn't have upload() method. Use save() method for saving the file.
// read image from temporary file
$img = Image::make($_FILES['image']['tmp_name']);
// save image
$img->save('foo/bar.jpg');
Refer this link for more details
IN my vue js ajax post am storing file like
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
//remove old file and retain new one
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
$user->picture = $path;
$user->save();
THe above works and the image is saved in the storage/app/public/images/users which is okay
But the database field is saved as public/images/users so when accessing the value in the frontend its not found
After several tests i found out that in the database i need to save the file as
storage/images/users //note path is not starting with public
so i changed the
$user->picture="storage/images/users".$imagename;
But now after doing this the part that removes old file fails
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
How do i adjust the delete part to also work.
UPDATE FOR FULL CONTROLLER CODE
public function changeProfilePic(Request $request){
if ($request->hasFile('profile_pic')) {
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
//remove old file and retain new one
if(\Storage::has($user->profile_pic)){
\Storage::delete($user->profile_pic);
}
$user->profile_pic = "storage/images/users".$imagename;
//if save fails delete the uploaded image
if($user->save()){
return response("true", 200);
}else {
\Storage::delete($path);
return response("false", 200);
}
}else{
return response("false", 200);
}
}
in mmy vue js during upload am using vue-image-crop-upload plugin
<image-uploader field="profile_pic"
...other stuff for plugin
url="/change-profile-picture"
langType="en"
:headers="headers"
img-format="png"></image-uploader>
laravel route
Route::post('/change-profile-picture', 'UserController#changeProfilePic');
This is the way i resolved it
After a quick check i found out that no matter what i try
Storage::has or Storage::exists
Aways returns false and `Storage::delete doesnt throw any error even if the file doesnt exists
Also a quick check on the file path i had to change the name stored on database from storage to public hence explde and implode
TRHe final code that works is
public function changeProfilePic(Request $request){
if ($request->hasFile('profile_pic')) {
$imagename = sha1(time()).".".$request->profile_pic->extension();
$path = $request->profile_pic->storeAs('public/images/users',$imagename);
$user = \Auth::user();
$olduserpicdata = explode("/",$user->profile_pic);
$olduserpicdata[0] = "public";
//remove old file and retain new one
Storage::delete(implode("/",$olduserpicdata));
$user->profile_pic = "storage/images/users/".$imagename;
//if save fails delete the uploaded image
if($user->save()){
return response("true", 200);
}else {
Storage::delete($path);
return response("false", 200);
}
}else{
return response("false", 200);
}
}
I tried so many time but this code is not working. I don't know why. It is a image upload form. This code worked for another form but here it's getting an error: Call to a member function isValid() on a non-object
$file = array('dest_img' => Input::file('dest_img'));
// checking file is valid.
if (Input::file('dest_img')->isValid()) {
$destinationPath = 'uploads'; // upload path
$extension = Input::file('dest_img')->getClientOriginalExtension(); // getting image extension
$fileName = $s.'.'.$extension;
$imgPath= $destinationPath.'/'.$fileName;
//return $imgPath;
// renameing image
Input::file('dest_img')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
//Session::flash('success', 'Upload successfully');
//return Redirect::to('tblaze_admin/bannerAdd');
$data=array(
'dest_title' =>$input['dest_title'],
'dest_desc' =>$input['dest_desc'],
'dest_img' =>$imgPath,
);
//$result=Cms::where('cms_id',$cms_id)->update($data);
$result=Destination::where('dest_id',$dest_id)->update($data);
if($result >0)
{
\Session::flash('flash_message','Destination Updated Successfull!!');
}
else
{
\Session::flash('flash_error_message','Destination Updation Failed!!');
}
}
I'm stuck at this code; please give a solution
Have you added enctype="multipart/form-data" to your <form> tag? Or if you're using the Form builder, 'files' => true?
Input::file('dest_img') is not an object. You might have not loaded the classes that define Input. Check that laravel is bootstrapped correctly.