image upload code is not working - laravel-4

i am new in laravel, i am facing a big problem and i can't solve this problem.
I am trying to upload image into my database and upload folder,but my code is not working,
Here is my controller code
public function store()
{
$rules=array(
'gallery_name'=>'required',
'image_title'=>'required',
'image'=>'required'
);
$file = Input::file('image');
$destinationPath = 'uploads/';
// If the uploads fail due to file system, you can try doing public_path().'/uploads'
$filename = str_random(32) . '.' . $file->getClientOriginalExtension();
//$filename = $file->getClientOriginalName();
//$extension =$file->getClientOriginalExtension();
//get all book information
$galleryInfo = Input::all();
//validate book information with the rules
$validation=Validator::make($galleryInfo,$rules);
$upload_success = Input::file('image')->move($destinationPath, $filename);
if($validation->passes())
{
//save new book information in the database
//and redirect to index page
if ($upload_success) {
//save in the Band table database
Gallery::create($galleryInfo);
return Redirect::route('galleries.index')
->withInput()
->withErrors($validation)
->with('message', 'Successfully created Gallery.');
}
else {
return Redirect::route('galleries.create')
->withInput()
->withErrors($validation)
->with('message', 'Image fields are incomplete.');
}
}
//show error message
return Redirect::route('galleries.create')
->withInput()
->withErrors($validation)
->with('message', 'Some fields are incomplete.');
}
please help me as soon.
Thank you.

Related

unlink image only if exists in laravel

While updating the user image unlink image from public folder if exists otherwise do update the user with image. Currently I have no image for user. And while updating user from profile section I am getting this error unlink('images/users') is a directory. I want if image exists for user then unlink the image and upload the new one otherwise just upload the new image.
My controller:
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
$image = $request->file('image');
if (isset($image)) {
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!file_exists('images/users')) {
mkdir('images/users', 0777, true);
}
if (file_exists('images/users')){
unlink('images/users/' . \auth()->user()->image);
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}else if (!file_exists('images/users')){
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}
}
return redirect()->back();
}
Try this. I haven't test it yet. Let me know if you have any questions.
Make sure to Import File: use File;
UPDATED
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
// Let get the current image
$user = Auth::user();
$currentImage = $user->image;
// Let compare the current Image with the new Image if are not the same
$image = $request->file('image');
// The Image is required which means it will be set, so we don't need to che isset($image)
if ($image != $currentImage) {
// To make our code cleaner let define a directory for DRY code
$filePath = public_path('images/users/');
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!File::isDirectory($filePath)){
File::makeDirectory($filePath, 0777, true, true);
}
$image->move($filePath, $imageName);
// After the Image has been updated then we can delete the old Image if exists
if (file_exists($filePath.$currentImage)){
#unlink($filePath.$currentImage);
}
} else {
$imageName = $currentImage;
}
// SAVE CHANGES TO THE DATA BASE
$user->image = $imageName;
$user->save();
return redirect()->back();
}
To store the image: $request->image->storeAs('images/users/', $file_name);
To delete an image: Storage::delete('images/users/'. $file_name);

Updating an image in laravel does not save to DB, only saves when adding new record

I have the form of a service where a name, description, and photo is required. When adding a new service the form works fine, everything is saved in the database.
Problem is when I want to change the photo and upload a new one its not working.
**Here is my controller method **, for both adding and updating service
public function post(ServiceRequest $request, Service $service)
{
$service = Service::firstOrNew(['id' => $request->get('id')]);
$service->id = $request->get('id');
$service->name = $request->get('name');
$service->description = $request->get('description');
$image = $request->file('photo')->store('services/');
$service->photo = $image;
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$name = time() . $service->name . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $name);
}
if ($request->has('photo')) {
$image = $request->file('photo');
}
$service->save();
Alert::success('Service Saved');
return redirect()->back();
// dd($service);
}
I need some assistance with updating the image and removing an old one that was added on update record.

Update an image in laravel

I want to update user image but it's not getting updated.
I tried with $request->hasFile('image') but when I return these statement it always returns false
here is my controller
if($request->hasFile('image'))
{
$file = $request->file('image');
$file->move(public_path().'/image/',$file->getClientOriginalName());
$file_name = $file->getClientOriginalName();
DB::table('settings')
->where('id', $id)
->update(['logo' => $file_name]);
}
when I write
return response()->json($request->hasFile('image'));
it will return always false
try use this one instead
if ($request->file('image')) {
// your image upload code here
}

Creating default object from empty value "error in laravel"

Hi I'm working on update products form of e-commerce site but when I try to edit details then it shows error "Undefined variable: fileName" and error line is:
Product::where(['id'=>$id])->
update(['product_name'=>$data['product_name'],
'product_code'=>$data['product_ code'],
'product_color'=>$data['product_color'],
'description'=>$data['description'],
'price'=>$data['price'],'image'=>$fileName]);
return redirect()->back()->with('flash_message_success','Product
updated successfully!');
or when i try to update image only then its error is: "Creating default object from empty value", or error line is:
$product->image = $filename;
this is code of ProductsController:
public function editProduct(Request $request, $id=null){
if($request->isMethod('post')){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
if($request->hasFile('image')){
$image_tmp = Input::file('image');
if($image_tmp->isValid()){
$extension = $image_tmp->getClientOriginalExtension();
$filename = rand(111,99999).'.'.$extension;
$large_image_path =
'images/backend_images/products/large/'.$filename;
$medium_image_path =
'images/backend_images/products/medium/'.$filename;
$small_image_path =
'images/backend_images/products/small/'.$filename;
// Resize Images
Image::make($image_tmp)->save($large_image_path);
Image::make($image_tmp)->resize(600,600)->save($medium_image_path);
Image::make($image_tmp)->resize(300,300)->save($small_image_path);
// Store image name in products table
$product->image = $filename;
}
}
if(empty($data['description'])){
$data['description'] = '';
}
Product::where(['id'=>$id])-
>update(['product_name'=>$data['product_name'],
'product_code'=>$data['product_code'],
'product_color'=>$data['product_color'],
'description'=>$data['description'],
'price'=>$data['price'],'image'=>$fileName]);
return redirect()->back()->with('flash_message_success','Product
updated successfully!');
}
//Get product details
$productDetails = Product::where(['id'=>$id])->first();
return view('admin.products.edit_product')-
>with(compact('productDetails'));
}
"Undefined variable: fileName"
There's a typo in your variable. Change $fileName to $filename.
i guess you need to do something like this
$product=new Product();
$product->image = $filename;
also where did you define $fileName in your code?

How to upload an image using Laravel?

The problem:
I want to upload an image to a mySQL database using Laravel.
what I have tried:
I looked for other stack-overflow questions but they weren't helpful.
the result I am expecting :
is to have the image name or path saved to a column in my table on the database , to retrieve and display it later as a post in a blog.
First you need the form on your view (don't forget the csrf token):
<form action="/image-upload" method="POST" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
And on your routes file add the route for POST method:
Route::post('image-upload', 'ImageUploadController#imageUploadPost');
Then on your Controller create the function that will validate and move your image to the 'public/images' folder.
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('images'), $imageName);
}
For better solution please read this: Laravel File Storage
Actually with Laravel it only involves a few lines of code. Let's say you have a user that has an avatar which is stored in the database. Here's how you would store and retrieve the avatar from the database:
1. First you'll need to have an avatar column in the users table that can store binary data. Depending on how large you want to allow the avatar image to be, the data type of the column can be one of the following:
BLOB up to 64KB
MEDIUMBLOB up to 16MB
LONGBLOB up to 4GB
2. To store the uploaded image in the database you can do this:
Route::post('user/{id}', function (Request $request, $id) {
// Get the file from the request
$file = $request->file('image');
// Get the contents of the file
$contents = $file->openFile()->fread($file->getSize());
// Store the contents to the database
$user = App\User::find($id);
$user->avatar = $contents;
$user->save();
});
3. To fetch and ouput the avatar you can do the following:
Route::get('user/{id}/avatar', function ($id) {
// Find the user
$user = App\User::find(1);
// Return the image in the response with the correct MIME type
return response()->make($user->avatar, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->avatar)
));
});
NOTE: Please have this in your mind, MySQL isn't a suitable solution to store BLOB. You may need to use an object storage service like Amazon S3.
Use this to upload image
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[//'movie_name'=>'required',
// // 'description'=>'required',
// //'video_url'=>'required',
// 'image'=>'required|mimes:jpeg,jpg,png,gif|required|max:10000',
// ]);
if ($request->hasFile('image') && $request->hasFile('image2')) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
else
{
if ( $request->hasFile('image2')) {
$file2 = $request->file('image2');
$bg_images = time().'.'.$file2->getClientOriginalExtension();
//$bg_images=$file2->getClientOriginalName();
$destinationPath ='assets/admin/uploads/bg_images/';
$file2->move($destinationPath,$bg_images);
//echo $destinationPath;exit();
//echo $bg_images;
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
//print_r($insert_data);exit();
}
if ($request->hasFile('image') ) {
$file = $request->file('image');
//$image=$file->getClientOriginalName();
$image = time().'.'.$file->getClientOriginalExtension();
$destinationPath ='assets/admin/uploads/image/';
$file->move($destinationPath,$image);
//echo $destinationPath;exit();
//echo $image."<br/>";
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
'image'=>$image,
//'bg_images'=>$bg_images,
'created_at'=>now(),
'updated_at'=>now()
);
// print_r($insert_data);exit();
}
if ( ! $request->hasFile('image2') && ! $request->hasFile('image') ) {
$insert_data=array('movie_name'=>$request->movie_name,
'description'=>$request->description,
'video_url'=>$request->video_url,
//'image'=>$image,
// 'bg_images'=>$bg_images,
'updated_at'=>now()
);
// print_r($update_data);exit();
}
}
//exit();
// echo $image;
//exit();
//print_r($insert_data);exit();
$insert=DB::table('movies')->insert($insert_data);
if ($insert) {
return redirect()->route('admin.list_movies')->withSuccess('Record saved');
}
else {
return redirect()->route('admin.list_movies')->withError('Record not saved');
}
}

Resources