I want to upload an image and retrieve in from database when i need this.My code is perfectly working to upload image but it's path did not save in database.In database it's showing Null.Here is my code:
if ($request->hasFile('profilePic')) {
$file = array('profilePic' => Input::file('profilePic'));
$destinationPath = 'img/'; // upload path
$extension = Input::file('profilePic')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('profilePic')->move($destinationPath, $fileName);
}else{
echo "Please Upload Your Profile Image!";
}
$profile->save();
My Question:
How to save image path into database?
And how to retrieve image from database?
Updated: Profile.php
class Profile extends Model
{
protected $table = "profiles";
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
}
In your code there should be like this:
$profile->profilePic = $fileName;
& then
$profile->save();
1.How to save image path into database?
To save your full image path in a database field, the code is:
$profile->profilePic = $destinationPath.$fileName;
$profile->save();
2.And how to retrieve image from database?
In your view file using blade engine, write HTML code like this. In the image src you have to provide profilePic data as shown in the below HTML code:
<img src="{{asset($profile->profilePic)}}"/>
try this
$path = $file->getRealPath();;
$pos = strpos($path,'/public/');
if ($pos !== false) {
$path = substr($path, $pos + 1);
}
$input['file'] = $path;
Related
possible "duplicate": Laravel - Delete images from storage / update post
I want laravel to delete the old image and replace it with new uploaded image in the edit form. I tried doing this:
if( $request->hasfile('violationStatement') ) {
$destination = 'violations/' . $violation->violationStatement;
// Deletes the file if it exists
if( File::exists($destination) ) {
File::delete($destination);
}
$file = $request->file('violationStatement');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('violations/', $filename);
$violation->violationStatement = $filename;
}
$violation->update();
But the image is not deleted nor updating. In addition, I want to have a condition when I just want to edit data without uploading new image...
Here is the routing:
// Traffic Violations
Route::controller(TrafficViolationController::class)->group(function () {
Route::get('violations', 'index')->name('violations.index'); // Index page (DataTable)
Route::get('violations/create', 'create')->name('violations.create'); // The form for adding new records
Route::post('violations/create', 'store')->name('violations.store'); // Add new to DB
Route::get('violations/edit/{violation}', 'edit')->name('violations.edit'); // The form for editing records
Route::put('violations/edit/{violation}', 'update')->name('violations.update'); // Update record to DB
Route::get('violations/{violation}', 'destroy')->name('violations.destroy'); // Delete from DB
});
First make sure of namespace
use Illuminate\Support\Facades\File;
Then edit $violation->update() to $violation->save();
And if the path in public folder use this method public_path() as this
$destination = public_path('violations/' . $violation->violationStatement);
But if the path in storage folder use this method storage_path() as this
$destination = storage_path('violations/' . $violation->violationStatement);
I use Intervention\Image\Facades\Image for uploading image And Illuminate\Support\Facades\File For Manage Directories. below Code replace Pic If Exist. think now you have 123.jpg and you want replace it. it replace old pic with new one. if your image name is difference you can delete old one.
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
//Get Data Of uploaded pic
$file = $request->file('violationStatement');
$srcPath = $file->getRealPath();
$size = $file->getSize(); // if You Need Pic Size
$extension = $file->getClientOriginalExtension();
//Start Uploading
$Image = Image::make($srcPath);
$destPath = public_path("violations");
File::ensureDirectoryExists($destPath); // Check Directory Exist Or Make
$filename = time() . '.' . $extension;
$Image->save($destPath.'/'.$filename);
at last I suggest add some unique thing to Your Image Name because it may two user upload picture at Same Time!!! and One Picture replaced.
I am building an SPA. I am getting base64 string from my vue component in my laravel controller. How can I convert base64 string to a file. Then upload the site into my laravel local storage and then save the path in the database table ?
I have googled almost every link and tried too many things. I even tried image intervention but the only thing I was able to achieve was to upload the file into the laravel storage but wasn't able to store the right path in the database table.
Here is my controller code
$team = new Team;
$team->hood_id = $user->hood->id;
$team->title = $request->title;
$team->max_no_of_players = $request->max_no_of_players;
$team->description = $request->description;
$team->about_us = $request->about_us;
$team->email = $request->email;
$team->contact_no = $request->contact_no;
$team->meetup_place = $request->meetup_place;
/**
* Image base64 converting code starts from here
*/
$image = $request->image;
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
$team->image = Storage::disk('public')->put($imageName, base64_decode($image));
I should be able to use Storage::url($image); when fetching the teams from database table. But right now I am not getting the correct path, Any help would be highly appreciated
In this way, you can fetch the file from the Base64 URL, I used this way.
$pos = strpos($fileBase64Url, ';');
$filetype = explode('/', substr($fileBase64Url, 0, $pos))[1]; //get file type
$contents = file_get_contents($fileBase64Url); //get the content from the URL
$unique_name = 'filename.' . $filetype; //file name
Storage::put('/public/folderName/' . $unique_name, $contents); //save to the directory
//$unique_name (Save this name to the Database)
And this is the path of this image file
http://127.0.0.1:8000/storage/folderName/filename.jpg (remove public form url)
currently i can store file name is database and in public folder of laravel but i want to store file path in database?
My Controller:
$image=$userProfile['image'];
$image1 = base64_decode($image);
$filename = time().'.'.$extension;
Storage::disk('public')->put($filename,$image1);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filename]);
How i can store image path in laravel and image name in public folder? i am sending image in json using base64.
Your help will be highly appreciated?
Use:
$image = $userProfile['image'];
$image1 = base64_decode($image);
$filename = time().'.'.$extension;
Storage::disk('public')->put($filename,$image1);
$filePath = Storage::disk('public')->getAdapter()->getPathPrefix();
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filePath.$filename]);
First type this command :
php artisan storage:link
it will create a symlink to public folder.
in your controller, you can write like this :
if ($request->file('image')) {
$file = $request->file('image')->store('images', 'public');
$new_product->image = $file;
}
this code will insert a random string included the path, so you can have something like this on your image column value 'images/shgsqwerfsd.jpg'
I am trying to upload an image with a random name, also when I update the image, I want the previous image to be deleted.
Code below:
$banner=$_FILES ['banner']['name'];
$upload="../image/banner/";
$target_file = $upload.basename($_FILES["banner"]["name"]);
$imagefiletype= pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["banner"]["tmp_name"], $target_file );
Any help will be appreciated.
When update your new images at that time first store old image name in variable. after update true then delete old image in your directory using "unlink" function.
$old_image = "xyz" // store old image name
after update query success
unlink('../image/banner/'.$old_image); // delete old image in your directory
You can do it like this.
$path = 'image/folder/'; $unique_name=time().uniqid(rand());
$File_with_location = $path . $unique_name . '.' . strtolower(pathinfo($_FILES['img']['name'], PATHINFO_EXTENSION));
$filename = $_FILES["img"]["tmp_name"];
move_uploaded_file($filename, $File_with_location);
for deleting old image you can use this
$path = './root/home/folder/file.jpg';
if (unlink($path)) {
echo 'success';
} else {
echo 'fail';
}
I cant save a image using the storage method.
If I do: $file->move(public_path().'/', $file->getClientOriginalName());
The image will get saved and I can open it in finder.
But if I save the image using:
$extension = $file->guessExtension();
$filename = 'thumnail_'.$id.'.'.$extension;
if ($file) {
$s3 = Storage::disk('public')->put($filename, $file);
}
It will also get saved to the folder but then I cant open it because the file is corrupted
And to be clear "file" is sent to my model from a controller: $file = $request->file('images');