How can I update image in edit view in laravel? - php

In laravel I have a field in my edit view named Profile Picture, whenever I click On edit button I got all the values from database in edit view but I don't get image, And If whenever I click on submit button everytime I have to upload image without that I can't process further I want If I not upload new image then form will automatic consider old profile pic
my blade file is like
<div class="col-md-6">
<div class="form-group">
<label for="photo">Profile Picture :<span class="danger">*</span> </label>
<div class="row">
<div class="col-md-9">
<input type="file" class="form-control" id="file" name="file">
</div>
<div class="col-md-3">
#foreach ($empProfilePic as $empProfilePicture)
#if($employee->id == $empProfilePicture->id)
<img src="uploads/images/{{ $empProfilePicture->file }}" id="profile-img-tag" height="100" width="100">
#endif
#endforeach
</div>
</div>
</div>
</div>
Controller File
public function updateEmployee(Request $request, $id)
{
$employee = User::find($id);
//Get inputs for personal detail
$firstName = $request->get('firstName');
$middleName = $request->get('middleName');
$lastName = $request->get('lastName');
$gender = $request->get('gender');
$city = $request->get('city');
$state = $request->get('state');
$localAddress = $request->get('localAddress');
$permanentAddress = $request->get('permanentAddress');
$personalEmail = $request->get('personalEmail');
$mobileNumber = $request->get('mobileNumber');
$companyEmail = $request->get('companyEmail');
$empId = $request->get('empId');
$department = $request->get('department');
$designation = $request->get('designation');
$status = $request->get('status');
$totalExperience = $request->get('totalExperience');
$aboutMe = $request->get('aboutMe');
$roleName = $request->get('role');
$role = $request->get('role');
if ($role == 'hr')
{
$role = '5c8a51ed650fbd5398503043';
}
else
{
$role = '5c8a51ed650fbd5398503044';
}
// //Store Image In Folder
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
$accountHolderName = $request->get('accountHolderName');
$accountNumber = $request->get('accountNumber');
$bankName = $request->get('bankName');
$ifscCode = $request->get('ifsc_code');
$panNumber = $request->get('panNumber');
$branchName = $request->get('branchName');
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;
//Update Image
$employee->file = $name;
$employee->personal_email = $personalEmail;
$employee->company_email = $companyEmail;
$employee->status = $status;
$personalDetail = ([
'emp_id' => $empId,
'first_name' => $firstName,
'middle_name' => $middleName,
'last_name' => $lastName,
'gender' => $gender,
'city' => $city,
'state' => $state,
'local_address' => $localAddress,
'permanent_address' => $permanentAddress,
'personal_email' => $personalEmail,
'mobile_number' => $mobileNumber,
'department' => $department,
'designation' => $designation,
'total_experience' => $totalExperience,
'about_me' => $aboutMe,
]);
$bankDetail = ([
'account_holder_name' => $accountHolderName,
'account_number' => $accountNumber,
'bank_name' => $bankName,
'ifsc_code' => $ifscCode,
'pan_number' => $panNumber,
'branch_name' => $branchName,
]);
$employee->status = $status;
$employee->personal_detail = $personalDetail;
$employee->bank_detail = $bankDetail;
$employee->save();
return redirect('list-of-employees')->with('Success', 'Data Updated Successfully!');
}
Will anyone will help, Thank you in advance

In controller:
Code for update file:
Its update only when you select a file for the update.
Here I use the Employee model you can replace with your model
public function update(Request $request, $id){
$employee = Employee::find($id);
if($request->file != ''){
$path = public_path().'/uploads/images/';
//code for remove old file
if($employee->file != '' && $employee->file != null){
$file_old = $path.$employee->file;
unlink($file_old);
}
//upload new file
$file = $request->file;
$filename = $file->getClientOriginalName();
$file->move($path, $filename);
//for update in table
$employee->update(['file' => $filename]);
}
}

Try this. If you get the file in post method, only then set the file variable of an employee.
// //Store Image In Folder
if (isset($_FILES['file'])) {
$file = $request->file('file');
$name = $file->getClientOriginalName();
$file->move('uploads/images', $name);
if (file_exists(public_path($name = $file->getClientOriginalName())))
{
unlink(public_path($name));
};
//Update Image
$employee->file = $name;
}
//Enter in database
$employee->role_id = $role;
$employee->role_name = $roleName;
$employee->username = $firstName;

Make the image input optional (don't add required) on the blade file and on the validation (controller) then check before updating as:
if ($request->hasFile('image')) {
// Perform image update
}

Related

How to add file in laravel through dropify data-default-file

Hello i am trying to show the image in the dropify field by fetching the image from database.But i am unable to do so .Kindly check my code.
`
<input type="file" class="dropify" name="profile_pic" data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}"/>
THE CONTROLLER IS
public function editUserForm($id)
{
$user = User::find($id);
return view('admin.users.edit-users',compact('user'));
}
public function updateUser(Request $request,$id)
{
$r1 = $request->validate([
'profile_pic' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048|',
'name' => 'required',
'email' => 'required|email',
'city' => 'required',
'phone_no' => 'required',
]);
if ($request->hasFile('profile_pic')) {
$imgName = uniqid() . '.' . $request->profile_pic->getClientOriginalExtension();
}
$user = User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->phone_no = $request->phone_no;
$user->profile_pic =$imgName;
$user->city = $request->city;
$user->update();
$path = public_path('uploads/driving');
if ($request->hasFile('profile_pic')) {
$request->profile_pic->move($path, $imgName);
}
return redirect()->route('users')->with('message', 'User info updated successfully!');
}
i created a url data-default-file="{{ url('/uploads/driving/'.$user->profile_pic) }}" but unable to show the image.

how to make first item of array active and rest inactive

I have multiple image uploader and i want only the first image to get true value and other false. I mean I have DB field name 'isPrimary' , so when I upload multiple images I want only first image get true value and other images get false value.
<div class="col-lg-12 p-t-20">
<label class="control-label col-md-3">Upload Room Photos</label>
<input type = "file" id = "image" name="image[]" multiple class="file" data-overwrite-initial="false"
data-min-file-count="1">
</div>
This is my controller for image store
if($request->hasfile('image')) {
$image = $request->image;
if(count($image) === 1){
$isPrime = $dataa['isPrimary'] = true;
}else{
///So here i need logic to make ('isPrimary') field to be true in only first image when there is multiple images is uploaded
}
foreach ($image as $photo) {
// dd($photo);
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
//
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
Image::create($dataa);
}
}
Sorry For my English, I am not good at cause it's my second language .
Thanks, in advance.
Try this
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=> (\Arr::first($image) == $photo) ? true : false,
];
Image::create($dataa);
}
$is_prime = true;
foreach ($image as $photo) {
$name = $photo->getClientOriginalName();
$filename = $photo->move(('storage/images/room_types/'), $name);
$dataa = [
'room_type_id' => $room_type->id,
'image' => $filename,
'isPrimary'=>$isPrime,
];
$is_prime = false;
}
Image::create($dataa);

How to upload my file and photo and add to databases

I want to upload a picture.
I wrote a codes for this ... but this photo is not added to the database at all. And Just, "else" is executed.
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$cover_image = $request ->file('cover_image');
$owner_id = 1;
//Check Image Upload
if($cover_image)
{
$cover_image_filename = $cover_image -> getClientOriginalName();
$cover_image -> move(public_path('images'), $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]
);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}`
what's the wrong?
1) Make sure you have added enctype="multipart/form-data" in your form and a <input type="file"> with field name="cover_image"
2) Create a new folder named images in your laravel public folder.
3) In your controller
public function store(Request $request){
//Get Request Input
$name = $request ->input('name');
$description = $request ->input('description');
$owner_id = 1;
//Check Image Upload
if( $request->hasFile('cover_image')) {
$cover_image = $request->file('cover_image');
$path = public_path(). '/images/';
$cover_image_filename = $cover_image->getClientOriginalName();
$cover_image->move($path, $cover_image_filename);
}
else{
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')-> insert([
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id
]);
//Redirect
return \Redirect::route('gallery.index') -> with('message', 'Gallery Created');
}
Hope it's helpful.

Laravel 5 Image Upload Incorrect Database Path

I have been having issues with my image upload input. I am attempting to create a file upload input into my Laravel 5 project but I am running into problems with the path that is saved into the database image table.
The form is working and is posting, however, when the database saves the path to the image it is inputting: /Applications/MAMP/tmp/php/phptvwTYW instead of taking just the file name.
Additionally, the file is being moved to the correct public/img folder.
Code
public function store(PostRequest $request)
{
$this->createPost($request);
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
Here is the sample Controller Function currently using in my project
public function postCreateInternal(CreateDocumentInternalRequest $request) {
$data_information = $request->only(['title', 'assigned_to', 'folder_id', 'document_source']);
if ($request->hasFile('file_name') && $request->file('file_name')->isValid()) {
$document = $request->file('file_name');
#creating file Name
$mytime = Carbon::now();
$date_now = $mytime->toDateTimeString();
$date_now = $this->prepareFileNameString($date_now);
$document_extension = $document->getClientOriginalExtension();
$document_name = $this->prepareFileNameString(basename($document->getClientOriginalName(), '.' . $document_extension));
$document_fullName = $document_name . "_" . ($date_now) . "." . $document_extension;
$data_information['file_type'] = $document->getMimeType();
$data_information['file_size'] = $document->getSize();
$data_information['file_name'] = $document_fullName;
$data_information['file_download_type'] = "Internal";
$document->move(public_path() . '/uploads/documents/', $document_fullName);
}
if ($pot = $this->document->create($data_information)) {
$this->notification_admin->sendCreateDocument($data_information);
return redirect()->route('documents')->with('success', trans('document.create.msg_success'));
// return redirect()->route('update/document', $pot->id)->with('success', trans('document.create.msg_success'));
}
return redirect()->route('create/document')->with('error', trans('document.msg_error'));
}
CreateDocumentInternalRequest basically using for File and other data validation as per Laravel 5
And View File seems to like:
{!! Form::open(["class"=>"form-horizontal","data-parsley-validate"=>"data-parsley-validate",'role'=>'form','files'=>true]) !!}
<div class="form-group required {{ $errors->first('file_name', ' has-error') }}">
{!!Form::label('file_name', trans('document.label.file_name'), array('class' => 'col-md-4 control-label left-label'))!!}
<div class="col-sm-6">
{!! Form::file('file_name') !!}
{!! $errors->first('file_name', '<span class="help-block">:message</span>') !!}
</div>
</div>
{!! Form::close() !!}
In my current implementation, first i'm checking file uploaded, rename filename with current timestamp and re upload my desire location.
If you need any help my provided method let me know to improve in better way.
this is very simple way:
public function store(PostRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$post = ($request->except(['image']));
$post['image'] = $image_name;
Post::create($post);
Session::flash('success_message', 'Post has been added successfully!');
return redirect('teacher');
}
public function profileUpdate($id)
{
if(!Entrust::can('profile_update_employee'))
return Redirect::to('/dashboard')->withErrors(Config::get('constants.NA'));
if(!Helper::getMode())
return Redirect::back()->withErrors(Config::get('constants.DISABLE_MESSAGE'));
$employee = User::find($id);
if(!$employee)
return Redirect::to('employee')->withErrors(Config::get('constants.INVALID_LINK'));
$rules = array(
'photo' => 'image|image_size:<=2000|max:100000',
'date_of_birth' => 'date',
'date_of_joining' => 'date',
'date_of_leaving' => 'date',
'employee_code' => 'required|unique:profile,employee_code,'.$employee->Profile->id.',id'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
return Redirect::to('/employee/'.$id."#basic")->withErrors($validator);
Activity::log('Profile updated');
$profile = $employee->Profile ?: new Profile;
$photo = $profile->photo;
$data = Input::all();
$profile->fill($data);
if(Input::get('date_of_birth') == '')
$profile->date_of_birth = null;
if(Input::get('date_of_joining') == '')
$profile->date_of_joining = null;
if(Input::get('date_of_leaving') == '')
$profile->date_of_leaving = null;
if (Input::hasFile('photo') && Input::get('remove_photo') != 1) {
$filename = Input::file('photo')->getClientOriginalName();
$extension = Input::file('photo')->getClientOriginalExtension();
$file = Input::file('photo')->move('assets/user/', $employee->username.".".$extension);
DB::insert('insert into ez_profile (id, photo) values ($id, $photo)');
$img = Image::make('assets/user/'.$user->username.".".$extension);
$img->resize(200, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save('assets/user/'.$user->username.".".$extension);
$profile->photo = $employee->username.".".$extension;
} elseif(Input::get('remove_photo') == 1){
File::delete('assets/user/'.$profile->photo);
$profile->photo = null;
}
else
$profile->photo = $photo;
$employee->profile()->save($profile);
return Redirect::to('/employee/'.$id.'/#basic')->withSuccess(Config::get('constants.SAVED'));
}
Try this:
public function store(PostRequest $request, Post $post) {
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$post->create([
'field1' => $val1,
'imageField' => $filename,
'field2' => $val2
]);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
I found the solution to my question.
I had to make some changes to the store and createPost functions within my controller to make this work.
For the controller I have:
public function store(PostRequest $request)
{
$destinationpath = public_path() . '/img/';
$filename = $request->file('image_url')->getClientOriginalName();
$request->file('image_url')->move( $destinationpath,$filename );
$this->createPost($request, $filename);
flash()->success('Your Post Has Been Created!');
return redirect('posts');
}
private function createPost(PostRequest $request, $new_url)
{
$post = Auth::user()->posts()->create($request->all());
$post->image_url = $new_url;
$post->save();
$this->syncTags($post, $request->input('tag_list'));
return $post;
}
I hope this helps anyone else that may be running into this same problem.
Thank you everyone for the help!
its because you save before moving,
//before moving
$request->file('image_url')->getPath(); // returns Applications/MAMP/tmp/php/php...
to have the full path of your new moved file you can do this
//After moving
$res = $request->file('image_url')->move( $destinationpath,$filename );
$my_new_path = $res->getPath(); // returns [public_path]/img/filename.jpg
you can save it by update your post after moving the file, or use event to move it when saving
look here http://laravel.com/docs/master/eloquent#events

Laravel Insert data without select file

Ok, when insert data in the database, in the form of my field is to image, but if you insert data without image, appears to me the following error.
Call to a member function getClientOriginalName() on a non-object
public function store() {
$unos = Input::all();
$obavezno = array('name' => 'required',
'number' => 'required|unique:os',
'zajednica' => 'required',
'slika' => 'image|size:3000',
);
$valid = Validator::make($unos, $obavezno);
if($valid->passes()) {
$biraci = new Biraci();
$filename = Input::file('slika')->getClientOriginalName();
$biraci->name = Input::get('name');
$biraci->slika = Input::file('slika')->move('public/uploads', $filename);
$biraci->path = $filename;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
return Redirect::to('biraci/dodaj')->with(array('ok' => 'Birac je uspjesno dodat.'));
} else {
return Redirect::to('biraci/dodaj')->withErrors($valid);
}
}
Try this:
if($valid->passes()) {
$biraci = new Biraci();
if (Input::hasFile('slika')) {
$filename = Input::file('slika')->getClientOriginalName();
}
$biraci->name = Input::get('name');
$biraci->slika = isset($filename) ? Input::file('slika')->move('public/uploads', $filename); : null;
$biraci->path = isset($filename) ? $filename : null;
$biraci->number = Input::get('number');;
$biraci->zajednica = Input::get('zajednica');
$biraci->save();
}
$filename = Input::file('slika')->getClientOriginalName();
// change to
$filename = Input::hasFile('slika') ? Input::file('slika')->getClientOriginalName() : null;

Categories