new image in update form didn't change - php

I made an update form wherein in i can edit and update current uploads in my renting shop project.
but i've been having this problem wherein the image isn't changing both in the page and database, but when i checked the storage/public/images it stores the same current image whenever i try to try again.
but the rest in my form is working fine and already changeable except the image.
Here is in my CarsController.php
public function update(Request $request, $id)
{
$car = Car::find($id);
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
if ($request->hasFile('image_location')) {
Storage::disk('public')->delete($car->image_location); // remove the old file.
$path = $request->image_location->store('images', 'public'); // save the new image.
$car->image_location = $path;
}
$car->save();
$request->session()->flash('message', 'The item has been updated.');
return redirect('/selections');
}
Here's the form
<div class="form-group">
<label>Image</label>
<input type="file" class="form-control" name="image_location" required>
</div>
i don't know what could possibly wrong. anyone please enlighten me. Thanks in advance. Anyway the migrated column name is image_location
also here's in my store()
public function store(Request $request)
{
$car = new car;
$car->car_brand = $request->car_brand;
$car->car_name = $request->car_name;
$car->description = $request->description;
$car->car_type_id = $request->car_type_id;
$path = $request->image_location->store('images', 'public');
$car->image_location = $path;
$car->availability = $request->availability;
$car->save();
$request->session()->flash('message', 'The item has been added.');
return redirect('/selections');
}

I'm afraid your code works perfectly for me.
You could try adding some log lines and see where the problem lies:
use Illuminate\Support\Facades\Log;
if ($request->hasFile('image_location')) {
Log::debug('File has been found in request.');
// Check if the old car image exists.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': ' does not exist'));
Storage::disk('public')->delete($car->image_location); // Remove the old file.
// Check if the old car image (if it existed) has been deleted.
Log::debug($car->image_location . (Storage::disk('public')
->exists($car->image_location)? ' exists': 'does not exist'));
$path = $request->image_location->store('images', 'public'); // save the new image.
// Check if the new file has been saved correctly.
Log::debug($path . (Storage::disk('public')
->exists($path)? ' exists': 'does not exist'));
$car->image_location = $path;
}
After uploading a new image, my storage/logs/laravel.log shows:
[2019-12-28 10:18:03] local.DEBUG: File has been found in request.
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif exists
[2019-12-28 10:18:03] local.DEBUG: images/WPMkdG56f4YXsd3IUJ3Ar1DbXF0QmtDz9bs0lKoI.gif does not exist
[2019-12-28 10:18:03] local.DEBUG: images/s9RtTdFSv0Is8AgxDWX5c09zG8SyU987RVeC0di5.gif exists

Related

how to fetch the old image in edit form in laravel ?what would be the code?

//Here is my edit form (image field)
I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I want to just use the photo that's already in the database. And not update the image field at all. But in my code whenever I am trying to without uploading new image form is not taking the old input value.
<div class="form-group">
<input type="file" name="image">
</div>
//this is the update function
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required',
'image' => 'mimes:jpeg,bmp,png,jpg'
]);
// get form image
$image = $request->file('image');
$slug = str_slug($request->name);
$category = Category::find($id);
if (isset($image))
{
// make unique name for image
$currentDate = Carbon::now()->toDateString();
$imagename = $slug.'-'.$currentDate.'-'.uniqid().'.'.$image->getClientOriginalExtension();
// check category dir is exists
if (!Storage::disk('public')->exists('category'))
{
Storage::disk('public')->makeDirectory('category');
}
// delete old image
if (Storage::disk('public')->exists('category/'.$category->image))
{
Storage::disk('public')->delete('category/'.$category->image);
}
// resize image for category and upload
$categoryimage = Image::make($image)->resize(1600,479)->stream();
Storage::disk('public')->put('category/'.$imagename,$categoryimage);
// check category slider dir is exists
if (!Storage::disk('public')->exists('category/slider'))
{
Storage::disk('public')->makeDirectory('category/slider');
}
// delete old slider image
if (Storage::disk('public')->exists('category/slider/'.$category->image))
{
Storage::disk('public')->delete('category/slider/'.$category->image);
}
// resize image for category slider and upload
$slider = Image::make($image)->resize(500,333)->stream();
Storage::disk('public')->put('category/slider/'.$imagename,$slider);
} else {
$imagename = $category->image;
}
$category->name = $request->name;
$category->slug = $slug;
$category->image = $imagename;
$category->save();
Toastr::success('Category Successfully Updated :)' ,'Success');
return redirect()->route('admin.category.index');
}
// When i click on the edit button it shows the No file Chosen it is not displaying the old image ..
you should change your validation
in STORE function, you should give an image and upload it (if it is required)
but in UPDATE function maybe the user does'nt want to change image and user only wants to change for exmaple just the name, so user can select no image in update
so your validation in UPDATE must be NULLABLE.
$this->validate($request,[
'name' => 'required',
'image' => 'nullable|mimes:jpeg,bmp,png,jpg'
]);

how to change value of a field before updating database in laravel

First let's go through my codes. Here is my CONTROLLER part:
public function store(Request $request){
$data=$request->all();
$adminProfile=AdminProfile::find(1);
$image = $request->file('admin_propic')->getClientOriginalName();
$gallery = new AdminProfile();
$gallery->admin_propic= $image;
$adminProfile->admin_propic=$image;
$request->admin_propic->move(public_path('uploaded'),$image);
$request->admin_propic = $image;
if($adminProfile){
$adminProfile->update($request->all());
}
else{
AdminProfile::create($data);
}
return view('dashboard part-admin.edit_profile');
}
now, the thing is, when I am updating profile picture (admin_propic), it's setting the path of temporary picture instead of it's original name. But, in my "uploaded" folder, the profile picture is being uploaded at it's real name. So, I tried to change it's value from the controller part. But it's not working.
** $image contains the desired value
try this:
public function store(Request $request){
$data=$request->all();
$adminProfile=AdminProfile::find(1);
$image = $request->file('admin_propic')->getClientOriginalName();
$gallery = new AdminProfile();
$gallery->admin_propic= $image;
$adminProfile->admin_propic=$image;
$request->admin_propic->move(public_path('uploaded'),$image);
// $request->admin_propic = $image; this will not work i think as request object is readonly as far as i know.
if($adminProfile){
// updated here
$data['admin_propic'] = $image
$adminProfile->update($data);
}
else{
AdminProfile::create($data);
}
return view('dashboard part-admin.edit_profile');
}

Can't create row because give null image path on form upload

I want to upload image and save data on database use form in view, but while press submit button, i get some error that is Call to a member function hasFile() on null when I have selected images on my computer, how to the fix that error so that i can upload image and saving data on database. Thanks for you answer.
Here code in controller :
public function UploadFile()
{
$file = Input::file('image');
if($file->hasFile('image'))
{
$name = $datas->kode_barang.'.jpg';
$file->move(public_path().'/assets/images/barang/', $name);
$newpath = public_path().'/assets/images/barang/'.$name;
$dataGambar = new GambarModel;
$dataGambar -> kode_gambar = $datas->kode_barang;
$dataGambar -> nama_gambar = $file->getClientOriginalName();
$dataGambar -> path = $newpath;
$dataGambar -> kategori = 'barang';
$dataGambar->save();
Session::flash('message', 'Berhasil menambahkan barang !');
return Redirect::to('/barang');
}
else
{
Session::flash('message', 'Upload tidak berhasil'.$file->getPathName() );
return Redirect::to('/barang');
}
}
Here some script form file on view :
{{ Form::label('image', 'Pilih gambar') }}
{{ Form::file('image') }}
Add enctype ="multipart/form-data" in your form tag.

Laravel upload photo on update

I have this form to edit article and change photo:
<h1>Edit: {{$article->title}}</h1>
<hr>
{!! Form::model($article, ['method'=>'PATCH','files' => true, 'action'=>['ArticlesController#update', $article->id]]) !!}
#include('articles.form',['submitButtonText'=>'Update Article'])
{!! Form::close() !!}
#include('errors.list')
now at Controller I have this function:
public function update($id, Requests\ArticleRequest $request)
{
$photo= 'http://nationaluasi.com/dru/content/hotelIcon.png';
$file = array('photo' => $request->file('photo'));
// setting up rules
$rules = array('photo' => 'required',); //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
$photo = 'http://nationaluasi.com/dru/content/hotelIcon.png';
}
else {
// checking file is valid.
if ($request->file('photo')->isValid()) {
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$photo = str_random(5).'.'.$extension; // renameing image
$request->file('photo')->move($destinationPath, $photo); // uploading file to given path
// sending back with message
}
else {
}
}
$article = Auth::user()->articles()->findOrFail($id);
$article['photo'] = $photo;
$article->update($request->all());
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
but now when I try to submit uploaded photo I get this result in column photo: C:\wamp\tmp\php21F4.tmp but also image is uploaded into /images folder...
What is the problem here? How to update article... also I want to say that is everything fine when I add article - add photo so on method store everything is the same and work fine...
UPDATE:
I try:
$article = Auth::user()->articles()->findOrFail($id);
$article['photo'] = $photo;
dd($photo);
and everything is fine, photo is uploaded succesfully just i dont update article['photo']... so problem is here:
$article->update($request->all());
But how to solve it? Why article['photo'] is not updated ?
I tried to correct your code, use this.
public function update($id, Requests\ArticleRequest $request)
{
$this->validate($request, [
'photo' => 'required|image|max:10000',
// validate also other fields here
]);
// checking file is valid.
if (!$request->file('photo')->isValid()) return redirect()->back()->withErrors(["photo" => "File is corrupt"]);
// file is valid
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$filename = str_random(5).'.'.$extension; // give a name to the image
$request->file('photo')->move($destinationPath, $filename); // uploading file to given path
// sending back with message
$article = Auth::user()->articles()->findOrFail($id); //if article id is unique just write Article::findOrFail($id)
$article_fields = $request->except('photo');
$article_fields['photo'] = $filename;
$article->update($article_fields);
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
I'll assume you're using Laravel 5. I believe the issue is this line:
$article->update($request->all());
The update method expects an array of column and value pairs. Your code above is giving it the original (unmodified) request which doesn't include your new photo location.
With Laravel you can actually get the article object, set the column directly within the object and then save the changes.
Try changing the last few lines of your method to:
$article = Auth::user()->articles()->findOrFail($id); // get the article
$article->photo = $photo; // set the photo column to your new location
$article->save(); // this will save your changes
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
Take a look at the Laravel documentation for more explanation.

How to store and retrieve image contents from the database using Laravel

I have to store and retrieve an image from the database.
I want to store an image instead of image path or image name. When I searched for it I only found solutions for storing an image path or name. So can someone tell me how to store and retrieve an image with its size in KBs from database?
This is my route.
Route::get('big_image/{id}/image', function ($id)
{
$user = big_image::find($id);
return response()->make($user->image, 200, array(
'Content-Type' => (new finfo(FILEINFO_MIME))->buffer($user->image)
));
});
This is my controller
public function new_store(Request $request ,$id){
$event_id = $id;
$img = new big_image;
$file = $request->file('image');
$contents = $file->openFile()->fread($file->getSize());
$img = big_image::find($id);
$img->image = $contents;
$img->image_name = $request->image_name;
$img->event_id = $event_id;
$img->save();
$images=DB::table('big_image')->where('event_id','=',$event_id)->get();
return view('image_upload',compact('images','id','response'));
}
My display.blade.php file
#extends('app')
#section('content')
<h2 style="text-align: center;margin-top: 10px;">Image Gallery</h2>
<span> add more pictures</span><br>
<span>Back to events</span><br>
#foreach($images as $item)
<div class="col-sm-4">
{{--<img src="data:image/jpeg;base64,'.base64_encode( $item->image ).'"/>;--}}
</div>
#endforeach
#stop
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. Assuming you're using MySQL, 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)
));
});
So to access the avatar of the user with an id equal to 10 you can just use this URL:
http://domain.com/user/10/avatar
You can store files in database in blob fields.
Maybe this link helps you
Then You can create url to your image:
Route::get('/images/{image}', function($image)
{
header("Content-type: image/jpeg");
//"select image from table where id = $image"
echo $here_I_get_my_img_from_DB;
});
and get img from url: /image/{img_id}

Categories