Image upload in Laravel - php

I want to upload an image much like a profile image to the project I am working with. I do not want multiple images that can be uploaded simultaneously. The previous image has to delete when a new image is uploaded.
Can anybody help me with this?
I am new to Laravel.

you can use these as reference.
This is for storing the data.
public function store(Request $request)
{
$input = $request->all();
//handle file upload
if ($request->hasFile('partner_img')) {
$fileNameWithExt = $request->file('partner_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('partner_img')->getClientOriginalExtension();
$partner_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('partner_img')->move('images/partners', $partner_img);
$input['partner_img'] = $partner_img;
} else {
$package_img = 'noimage.jpg';
}
$partner = $this->partnerRepository->create($input);
Flash::success('Partner saved successfully.');
return redirect(route('partners.index'));
}
this is for updating.
public function update($id, Request $request)
{
$input = $request->all();
$partner = $this->partnerRepository->findWithoutFail($id);
if (empty($partner)) {
Flash::error('Partner not found');
return redirect(route('partners.index'));
}
if ($request->hasFile('partner_img')) {
$fileNameWithExt = $request->file('partner_img')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extension = $request->file('partner_img')->getClientOriginalExtension();
$new_partner_img = $filename . '_' . time() . '.' . $extension;
$path = $request->file('partner_img')->move('images/partners', $new_partner_img);
Storage::delete('partners/'.$partner->partner_img);
$input['partner_img']= $new_partner_img;
}
$partner = $this->partnerRepository->update($input, $id);
Flash::success('Partner updated successfully.');
return redirect(route('partners.index'));
}

I did it this way along with some other fields. Now it is solved:
public function update(Request $request)
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'file' => 'required|max:100000|mimes:doc,docx,pdf',
'email' => 'required|email',
]);
$peoples = People::find($request->id);
$peoples->Name = $request->name;
$peoples->Email = $request->email;
$peoples->Address = $request->address;
if ($request->hasFile('image')) {
if ($peoples->image) {
File::delete(public_path($peoples->image));
}
$imageName = time() . '.' . request()->image->getClientOriginalExtension();
request()->image->move(public_path('images/'), $imageName);
$peoples->image = $imageName;
}
if ($request->hasFile('file')) {
if ($peoples->File) {
File::delete(public_path($peoples->File));
}
$fileName = time() . '.' . request()->file->getClientOriginalExtension();
request()->file->move(public_path('files/'), $fileName);
$peoples->File = $fileName;
}
$peoples->update();
$peoples->save();
}

Related

How to Replace and Delete previous files uploaded, when Edit a record in Laravel 4.2

I use laravel 4.2, because this project has been around for years. :)
Now, how can i replace and delete previous files uploaded in public
directory, when edit a record ?
Given the following Controller code ( Update Methode ) :
public function update($id)
{
$idd = Sentry::getUser()->id;
try {
$validator = Validator::make(
Input::all(),
array(
'first_name' => 'required',
'last_name' => 'required',
'eng_certificate' => 'image|mimes:png,jpeg,jpg|max:1100',
'profile_img' => 'image|mimes:png,jpeg,jpg|max:1100',
)
);
if ($validator->passes()) {
$profile = User::find($id);
$profile->first_name = Input::get('first_name');
$profile->last_name = Input::get('last_name');
if (Evidence::where('user_id', $idd)->count() == 0) {
$evidence = new Evidence;
$evidence->user_id = $idd;
$evidence->created_at = jDate::forge()->time();
} else {
$evidence = Evidence::where('user_id', $idd)->first();
$evidence->updated_at = jDate::forge()->time();
}
if (Input::hasFile('eng_certificate')) {
$image = Input::file('eng_certificate');
$destinationPath = 'uploads/evidence';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->eng_certificate = $image_filename;
$evidence->save();
}
}
if (Input::hasFile('profile_img')) {
$image = Input::file('profile_img');
$destinationPath = 'uploads/evidence/profile_img/';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$image_filename = sha1($filename) . '-' . rand(0, 1000) . '.' . $extension;
$image_uploadSuccess = $image->move($destinationPath, $image_filename);
if ($image_uploadSuccess) {
$evidence->profile_img = $image_filename;
$evidence->save();
}
}
$profile->save();
return Redirect::route('cpanel.home')->with('success', 'اطلاعات پروفایل شما با موفقیت بروز گردید.');
}
else {
return Redirect::back()->withInput()->withErrors($validator->messages());
}
}
catch (LoginRequiredException $e) {
return Redirect::back()->withInput()->with('danger', $e->getMessage());
}
}
How can I fix it?
Thank you.
find out current file location
use php unlink function
https://www.w3schools.com/php/func_filesystem_unlink.asp
You can interact with the filesystem by using: Laravel Filesystem
For example:
Storage::delete('file.jpg');
See: https://laravel.com/docs/5.8/filesystem#deleting-files

Creating default object from empty value during update with eloquent relationship in laravel

I am trying to update 'employee' and 'employee_details' in which I used one to one relationship. During the update, I am getting this error exactly in $employeeDetail->card_no = $request->card_no, in employeeDetail and I searched and tried to implement the possible solutions but still getting this error. Would someone help me to solve this problem, please?
EmployeeController.php
public function update(Request $request, $id)
{
$employee = Employee::find($id);
$employee->card_no = $request->card_no;
$employee->name = $request->name;
$employee->father_name = $request->father_name;
$employee->mother_name = $request->mother_name;
$employee->spouse_name = $request->spouse_name;
$employee->permanent_add = $request->permanent_add;
$employee->present_add = $request->present_add;
$employee->area = $request->area;
$employee->dob = Carbon::parse($request->dob)->format('Y-m-d');
$employee->blood_group = $request->blood_group;
$employee->nid_number = $request->nid_number;
$employee->mobile = $request->mobile;
$employee->reference_name = $request->reference_name;
$employee->reference_nid = $request->reference_nid;
$employee->reference_mobile = $request->reference_mobile;
$employee->reference_add = $request->reference_add;
if (! $request->photo == '') {
$employee->photo = $request->photo;
if ($file = $request->file('photo')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/photo';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old photo if exists
if (File::exists(public_path() . $folderName . $employee->photo)) {
File::delete(public_path() . $folderName . $employee->photo);
}
//save new file path into db
$employee->photo = $safeName;
}
}
if (! $request->nid_file == '') {
$employee->nid_file = $request->nid_file;
if ($file = $request->file('nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old nid_file if exists
if (File::exists(public_path() . $folderName . $employee->nid_file)) {
File::delete(public_path() . $folderName . $employee->nid_file);
}
//save new file path into db
$employee->nid_file = $safeName;
}
}
if (! $request->reference_nid_file == '') {
$employee->reference_nid_file = $request->reference_nid_file;
if ($file = $request->file('reference_nid_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/nid';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old reference_nid_file if exists
if (File::exists(public_path() . $folderName . $employee->reference_nid_file)) {
File::delete(public_path() . $folderName . $employee->reference_nid_file);
}
//save new file path into db
$employee->reference_nid_file = $safeName;
}
}
if (! $request->character_file == '') {
$employee->character_file = $request->character_file;
if ($file = $request->file('character_file')) {
$extension = $file->getClientOriginalExtension() ?: 'png';
$folderName = '/uploads/employees/character-certificate';
$destinationPath = public_path() . $folderName;
$safeName = str_random(10) . '.' . $extension;
$file->move($destinationPath, $safeName);
//delete old character_file if exists
if (File::exists(public_path() . $folderName . $employee->character_file)) {
File::delete(public_path() . $folderName . $employee->character_file);
}
//save new file path into db
$employee->character_file = $safeName;
}
}
if ($employee->save()) {
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
return back()->with('success', 'Congratiolations! You appointed a new employee.');
}
}
Change
From
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
$employeeDetail->card_no = $request->card_no,
$employeeDetail->section_id = $request->section_id,
$employeeDetail->designation_id = $request->designation_id,
$employeeDetail->salarygrade_id = $request->salarygrade_id,
$employeeDetail->joining_date = Carbon::parse($request->joining_date)->format('Y-m-d'),
$employeeDetail->quit_date = $request->quit_date,
]);
to
$employeeDetail = EmployeeDetail::where(['employee_id' => $id])
->update([
'card_no' => $request->card_no,
'section_id' => $request->section_id,
'designation_id' => $request->designation_id,
'salarygrade_id' => $request->salarygrade_id,
'joining_date' => Carbon::parse($request->joining_date)->format('Y-m-d'),
'quit_date' => $request->quit_date,
]);

Laravel : How to save multiple image file to database

I want to save multiple image files with different field in database such as product_image, feature_image, slurp_image. I used following controller method to save the image files
public function store(Request $request)
{
$product = new Product();
if($request->hasFile('product_image'))
{
$file = Input::file('product_image');
$imageName = time().'.'.$request->product_image->getClientOriginalExtension();
$product->product_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('feature_image'))
{
$file = Input::file('feature_image');
$imageName = time().'.'.$request->feature_image->getClientOriginalExtension();
$product->feature_image = $imageName;
$file->move('images/', $imageName);
}
if($request->hasFile('slurp_image'))
{
$file = Input::file('slurp_image');
$imageName = time().'.'.$request->slurp_image->getClientOriginalExtension();
$product->slurp_image = $imageName;
$file->move('images/', $imageName);
}
// dd($product->product_image);
// dd($product->feature_image);
// dd($product->slurp_image);
$product->save();
}
when i dd() the $product->product_image,$product->feature_image, $product->slurp_image i saw different different file name , but after it stored into the database i saw same file stored into database in different different field.
anyone help to find out what could be the solution please?
When you're uploading multiple images at once you'd be passing through an array of images.
This is what my controller function has looked like when I've done this previously.
public function multiple_upload() {
// get the files
$files = Input::file('images');
// counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach ($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads'; // upload folder in public directory
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
// save into database
$extension = $file->getClientOriginalExtension();
$entry = new Uploads();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $filename;
$entry->filename = $file->getFilename().'.'.$extension;
$entry->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('upload');
} else {
return Redirect::to('upload')->withInput()->withErrors($validator);
}
}
In your example, I'd image it would be more like this
$product = new Product();
//upload multiple files
$files= [];
if($request->file('leftimage')) $files[] = $request->file('leftimage');
if($request->file('Middleimage')) $files[] = $request->file('Middleimage');
if($request->file('Rightimage')) $files[] = $request->file('Rightimage');
foreach($files as $file)
{
if(!empty($file))
{
$filename[] = $file->getClientOrginalName();
if(isset($filename)){
$file->move(base_path().'/frontend/sidimage/',end($filename));
}
}
$product->image1 = $filename[0];
$product->image2 = $filename[1];
$product->image3 = $filename[2];

Laravel file name database

In Laravel 5.3 I'm uploading files like this:
public function upload(Request $request, User $user, $directory)
{
if($request->hasFile('attachment'))
{
$attachments = $request->file('attachment');
foreach ($attachments as $attachment) {
$fileName = $attachment->store('users/' . $user->id . '/' . $directory);
$file = new File;
$file->path = $fileName;
$file->user_id = $user->id;
$this->files()->save($file);
}
}
}
So it's being stored like this:
How do I store a random name (path) instead of a entire path?
(Random unique name something like: 7b11ae012907b5811cb6985d39e16052)
public function upload(Request $request, User $user, $directory)
{
if($request->hasFile('attachment'))
{
$random_name=rand(5, 15);
$attachments = $request->file('attachment');
foreach ($attachments as $attachment) {
$fileName = $attachment->store('users/' . $user->id . '/' . $random_name);
$file = new File;
$file->path = $fileName;
$file->user_id = $user->id;
$this->files()->save($file);
}
}
}
I've done it like this:
public function upload(Request $request, User $user, $directory)
{
if($request->hasFile('attachment'))
{
$attachments = $request->file('attachment');
foreach ($attachments as $attachment) {
$random = str_random(30);
$filename = $random . $attachment->getClientOriginalName();
$attachment->storeAs('users/' . $user->id . '/' . $directory, $filename);
$file = new File;
$file->path = $filename;
$file->user_id = $user->id;
$this->files()->save($file);
}
}
}

Multiple Image Upload in Laravel 5.2

Finally I can upload and move the images, but now I want to create a multiple upload images on Laravel. Is that possible? Did I have to use array to make it?
Can I just modify a little bit from this code?
It's on my ProductController.php
$picture = '';
if ($request->hasFile('images')) {
$file = $request->file('images');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Thank you.
Note: My code above is from a kindhearted person on stackoverflow, thanks again ;)
At your frontend form you'll have to use your field attribute name like
name="images[]"
And your controller code would be like this.
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images';
$file->move($destinationPath, $picture);
}
}
if (!empty($product['images'])) {
$product['images'] = $picture;
} else {
unset($product['images']);
}
Your input from $_POST will be coming in as an array. All you need to do is to iterate through it:
$picture = '';
if ($request->hasFile('images')) {
$files = $request->file('images');
foreach($files as $file){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$request->file('images')->move($destinationPath, $picture);
}
}
Slight modified code to upload multiple image.
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('images');
$picture = array();
if($request->hasFile('images')) :
foreach ($input as $item):
$extension = $item->getClientOriginalName();
$name = date('Ymd') . '.' . $extension;
$destinationPath = base_path() . '/uploads/images/';
$item->move($destinationPath, $name);
$arr[] = $name;
endforeach;
$picture = implode(",", $arr);
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple pictures are uploaded successfully');
return redirect('/image-upload');
}

Categories