saving image in database and show in view laravel 5.6 - php

i want to store image in my database as client agreement but i can't save any thing in database just the path i give manually here is what i have done
controller :
$filename = $request->file('agreement')->store('public/images');
$client = Client::create([
'title' => $request->title,
'description' => $request->description,
'fax'=>$request->fax,
'adrress1'=>$request->adrress1,
'telephone1'=>$request->telephone1,
'client_type'=>$request->client_type,
'sellpercent'=>$request->sellpercent,
'agreement'=>'uploads/agreement/'. $filename,
view :
.
.
.
<div class="form-group row">
<label class="col-form-label col-lg-2">test image</label>
<div class="col-lg-10">
<input type="file" name="agreement" class="form-control-plaintext">
</div>
</div>
<button type="submit" class="btn btn-primary btn-raised legitRipple">submit</button>
with this code i get this error on store function
Call to a member function store() on null
and if i remove store function i just save null in database

Firstly add enctype='multipart/form-data' in your form tag as an attribute.
Secondly,
replace $filename = $request->file('agreement')->store('public/images'); with $filename = $request->file('agreement')->move('public/images');
Hope that helps.

Related

Laravel errors while storing a file

I am working on a laravel crud project. Now i want to store files like .xlsx and .docx
But i keep getting errors in my controller and browser:
Controller:
public function store(Request $request)
{
$request->validate([
'title'=>'required',
'description_short'=>'',
'description_long'=>'',
'file'=>'',
'language_id'=> [
'required', 'exists:language,id'
],
]);
$fileName = $request->file->getClientOriginalName();
$filePath = 'files/' . $fileName;
$path = Storage::disk('public')->put($filePath, file_get_contents($request->file));
$path = Storage::disk('public')->url($path);
$file = new File([
'title'=> $request->get('title'),
'description_short'=> $request->get('description_short'),
'description_long'=> $request->get('description_long'),
'file'=>$request->get('file'),
'language_id'=> $request->language_id,
]);
$file->save();
return back();
}
Here i get the error: Undefined method 'url'
Create page:
<form method="post" action="{{ route('admin.language.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">{{('name')}}</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="value">{{('file')}}</label>
<input type="file" class="form-control" name="file"/>
</div>
<button type="submit" class="btn btn-primary">Add language</button>
</form>
the browser error i get is : Call to a member function getClientOriginalName() on string.
if i need to provide more information i will gladly do so!
file is reserved keyword in Request class to get submitted Files in post method.
You can not use file in input. So first you have to change file name in input box.
After that you can do like below.
$request->file('file_input_name')->getClientOriginalName();
$file = $request->file->getClientOriginalName();
fixed it

Laravel explode() array multiplefile

hello i have been create an multiple upload file in my add-modal.php something like this :
and the attachment is successfully implode() into array, here is my controller.php, which used to insert into my DB :
public function create(Request $request)
{
$datatest=array();
$request->validate([
'attachment_name' => 'nullable',
'attachment_name.*' => 'file|mimes:pdf|max:5048',
]);
if($files = $request->file('attachment_name'))
{
foreach($request->file('attachment_name') as $image )
{
$name = date('dmY') . "-" .$image->getClientOriginalName();
$image->move(public_path().'/storage/file/', $name);
$datatest[] = $name;
}
}
$insert['attachment_name'] = implode("|",$datatest);
MediaOrder::create($insert);
flash_success_store('Media Order successfully added.');
if ($request->ajax()){
return redirect_ajax_notification('media-order.index');
}else{
return redirect_ajax('media-order.index');
}
}
and then here is the attachment_name or file in the datatable :
so i would like to explode() the attachment_name, then create a download file for each attachment_name array, here is my view-modal-blade.php which contain the download button :
as for now each attachment_name or the file .pdf is still in one value, here is my view-modal-blade.php value which used to placeholder the attachment_name value :
<div class="row mg-t-20">
<label class="col-sm-4 form-control-label">ATTACHMENT:</label>
<div class="col-sm-8 mg-t-10 mg-sm-t-0 input-group control-group increment">
<input name="attachment_name[]" id="attachment_name_view" class="form-control" readonly></input>
<div class="input-group-btn">
<button class="btn btn-primary" type="button"><i class="fa fa-save"></i></button>
</div>
</div>
</div>
so my question is :
Is there a way to foreach and explode() the attachment_name based on the data id an then put theexplode() value like the first image?, so user can download each attachment_name file individualy? or maybe someone have an better alternate solution, thank you!.
Progress :
i have tried using foreach(explode('|', $data->attachment_name)) but the attachment_name ended up becomde undefined for the attachment_name. i will provide anything that might able to help, and apologize for my english.

Get the actual file name and extention from image file in laravel

When I am uploading an image to the form and returning it from the controller, the image name and extention are changing.I am a beggar, so if I make a mistake while asking a question, I would like to apologize.
This is my form:
<form action="{{ route('admin.slider.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<label class="control-label">Image</label>
<input type="file" name="image">
</div>
</div
<button type="submit" class="btn btn-success">Save</button>
</form>
This is my controller:
public function store(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,bmp,png,jpg',
]);
$image = $request->file('image');
return $image;
}
My image file name is :demo.jpg
Controller return result is like that:
C:\xampp\tmp\php5E86.tmp
This is the same result when I give another picture, only the last four characters are changing.
C:\xampp\tmp\phpF239.tmp
It is very helpful to know why I am getting .tmp file return.
use getClientOriginalName to get orginal file name
$request->image->getClientOriginalName()
To get file extension
$request->image->extension();
or
$name = $request->file('image')->getClientOriginalName();
$extension = $request->file('image')->extension();
Ref:https://laravel.com/docs/8.x/filesystem#other-uploaded-file-information

How to keep previously inserted data if I send blank data while updating through UpdateOrCreate method of Laravel Eloquent?

I am new in Laravel. I am using the UpdateOrCreate method of Laravel and I am trying to update some fields of the form and other fields will be as like as earlier. Let, I have three fields in the form which are user_bio, user_image, user_cover_image. I want to update uesr_bio only. I tried various way but I failed. I need to update will fields together! How can I solve this issue?
Here are my codes:
profile.blade.php (front-end view):
<div class="card">
<div class="card-header"> প্রোফাইল </div>
<div class="card-body">
<form action="profile/store" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="user_bio">Bio:</label>
<input type="text" class="form-control" id="user_bio" name="user_bio">
</div>
<div class="form-group">
<label>Upload your profile picture:</label>
<input type="file" class="form-control" name="profilepicture" id="profilepicture">
</div>
<div class="form-group">
<label>Upload your cover photo:</label>
<input type="file" class="form-control" name="coverphoto" id="coverphoto">
</div>
<button type="submit" class="btn btn-default" name="submit" value="submit">Submit</button>
</form>
</div>
</div>
ProfileController:
/** User Profile Picture (with URL) Storing Process Starts here **/
$image = $request->file('profilepicture');
$imagenewname= rand() .'.'. $image-> getClientOriginalExtension();
$path = $request->file('profilepicture')->storeAs(
'public/UserImages', $imagenewname
);
$imageName = "UserImages/".$imagenewname;
/** User Profile Picture (with URL) Storing Process Ends here **/
/** User Cover Photo (with path) Storing Process Starts here **/
$coverphoto = $request->file('coverphoto');
$coverphotoname= rand() .'.'. $coverphoto-> getClientOriginalExtension();
$coverphotopath = $request->file('coverphoto')->storeAs(
'public/CoverPhotos', $coverphotoname
);
$coverPhotoName = "CoverPhotos/".$coverphotoname;
/** User Cover Photo (with path) Storing Process Ends here **/
$check = Profile::updateOrCreate(['user_id' => $request->user_id], ['user_bio' => $request->user_bio, 'user_image' => $imageName, 'user_cover_image' => $coverPhotoName]);
This code will update only bio if the user already exist. otherwise it will create user with image and cover image:
$check = Profile::updateOrCreate(['user_bio' => $request->user_bio, 'user_image' => $imageName, 'user_cover_image' => $coverPhotoName], ['user_bio' => $request->user_bio]);

decode and move base64 encoded image in laravel

I am trying to implement a image upload with other form elements with dropzone.js in laravel. So far I've managed to display the drag and drop image upload view with other form elements. And also get POST details from the submitted form. But when dropzone is passing the uploaded image to the database data save function it encode image with base64. I think I've managed to get the file extension also. And when I submit the button it gives me this error "Call to a member function move() on string" . Please put me in the right direction.
Here is the Form
<form class="form-horizontal" action="{{ route('save-slider-content') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderTitle" id="sliderTitle" placeholder="Title of the post goes here">
</div>
</div>
<input type="hidden" name="date" id="date" value="<?php echo date("d-m-Y"); ?>">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Image</label>
<input hidden id="file" name="file"/>
<div class="col-sm-10">
<div class="dropzone needsclick dz-clickable" id="fileUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Link</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderLink" id="sliderLink" placeholder="Provide a link">
</div>
</div>
</div><br>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
<!-- /.box-footer -->
</form>
Here is the dropzone configuration
<script type="text/javascript">
Dropzone.options.fileUpload = {
url: "save-slider-content",
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
</script>
Route
Route::post('store-slider-content', [ 'as' => 'save-slider-content', 'uses' => 'SliderContent#save_slider_data']);
save_slider_data function in Controller
public function save_slider_data(Request $request)
{
$slider = new Slider;
$slider->title = $request->sliderTitle;
$slider->title_sin = $request->sliderTitleSin;
$slider->date = $request->date;
$slider->link = $request->sliderLink;
$file = $request->file;;
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = time().'.'.$mime_type;
$image_data->move(public_path('slider_uploads'), $imageName);
return response()->json(['success'=>$imageName]);
$slider->img_url = $imageName;
$slider->save();
}
Edited to include the logic for either Symfony\Component\HttpFoundation\File\File or Illuminate\Support\Facades\File (Illuminate\Filesystem\Filesystem)
move is a method of a File object, but $image_data is just a string. So one thing you could do is write the decoded image to a temp file, instantiate a File of it, and move it, like
//... your code ...
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
// ... and then:
//grab a new tmp file
$tmpFilePath=sys_get_temp_dir().'/'.uniqid();
//write the image to it
file_put_contents($tmpFilePath, $image_data);
//move it.
//give it a name
$imageName = time().'.'.str_replace("image/","",$mime_type);
//if using Symfony\Component\HttpFoundation\File\File;
//get an instance of File from the temp file and call ->move on it
$tmpFile=new File($tmpFilePath);
$tmpFile->move(public_path('slider_uploads'), $imageName);
//or if using File facade
File::move($tmpFilePath, public_path("slider_uploads/$imageName"));
//...and then, back to your code...
$slider->img_url = $imageName;
$slider->save();
return response()->json(['success'=>$imageName]);
}
You can do this:
In config/filesystems.php, register a new disk slider_uploads
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'slider_uploads' => [
'driver' => 'local',
'root' => public_path('slider_uploads')
]
]
And then use your new disk in storing your image
$image_data = $request->file;
#list($type, $image_data ) = explode(';', $image_data );
#list(, $image_data ) = explode(',', $image_data );
if($image_data !=""){ // storing image in public/slider_uploads/ Folder
\Storage::disk('slider_uploads')->put($imageName, base64_decode($image_data ));
}

Categories