laravel pdf to view add watermark using( Barryvdh\DomPDF) - laravel

my problem(not show pdf contents when this url(127.0.0.1:8081/php_tutorial.pdf))
Controller
public function generatePDF()
{
$data = [
'title' => 'Welcome to ',
'pdf' => '127.0.0.1:8081/php_tutorial.pdf',
'date' => date('m/d/Y')
];
$pdf = PDF::loadView('pdf',$data);
$pdf->setPaper('L');
$pdf->output();
$canvas = $pdf->getDomPDF()->getCanvas();
$height = $canvas->get_height();
$width = $canvas->get_width();
$canvas->set_opacity(.2,"Multiply");
$canvas->page_text($width/5, $height/2, 'This Is Watermark text', null,
70, array(0,0,0),2,2,-30);
return $pdf->stream('result.pdf');
}
view (blade)
{{ $title }}
<iframe src="{{ $pdf }}" width="100%" height="500px">

Firstly You need to create view to load all your PDF Views.
Then in your controller query your data
public function PDFSlip($id)
$data = ModelName::get()
$customPaper = array(0,0,600.00,310.80);
$pdf = PDF::loadView('pdf\bookingDetailPDF', compact('data'))-
>setPaper($customPaper, 'portrait');;
return $pdf->download('PDFNAME.pdf');
}
Then your file will be downloaded in the local directory and also pdf is loaded into the new tab.

Related

upload image as optional in laravel 8

I want to upload image using laravel 8, and I use following code:
$post = new Post;
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
It is working fine, but I got error Call to a member function getClientOriginalName() on null while image is empty.
It's because, suprise, image is empty while image is empty
Add condition to check uploaded image
$post = new Post;
$post->title = $req->input('title');
if($req->image_name)
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->image_name = $upload_image_name;
}
$post->save();
If image is required - add validation in action beginning - but right way for it - make validation in Form Request
$request->validate([
'image_name' => 'required|image',
'title' => 'required|string'
]);
If image is not required - change your migration and make posts.image_name nullable
I use following code but I don't think this is conventional way. Here is the code:
if($req->hasFile('image_name')){
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
}
else
$upload_image_name = "Noimage";
$post = new Post;
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
As I used my last laravel project.
$image = $request->file('thumbnail');
if (isset($image)) {
$imageName = date('y_m_d') . "_" . uniqid().".".$image->getClientOriginalExtension();
if (!Storage::disk('public')->exists('thumbnail')) {
Storage::disk('public')->makeDirectory('thumbnail');
}
$postImage = Image::make($image)->stream();
Storage::disk('public')->put('thumbnail/' . $imageName, $postImage);
} else {
$imageName = "";
}
$post = new Post;
$post->title = $request->title;
$post->image_name = $imageName;
$post->save();
image_name column should be nullable.

Image saving in database as C:\wamp64\tmp\phpAE1C.tmp instead of saving in public/images

I am trying to edit/update an image in a user table, when I select a new image and submit the form the image name doesn't get stored in the database instead this C:\wamp64\tmp\phpAE1C.tmp get saved in the image column, I don't know why, Please help if u know why.
The UsersController
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required|string|max:225',
'email' => 'required|string|email|max:255|unique:users,email,'.auth()->id(),
'password' => 'sometimes|nullable|string|min:6|confirmed',
]);
$user = auth()->user();
//Handle avatar Upload
if ($request->hasFile('avatar')) {
// Get filename with extention
$filenamewithExt = $request->file('avatar')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenamewithExt, PATHINFO_FILENAME);
// Get just Extention
$extention = $request->file('avatar')->getClientOriginalExtension();
// Filename to store
$filenameToStore = $filename.'_'.time().'.'.$extention;
// Upload Image
$path = $request->file('avatar')->storeAs('public/avatars', $filenameToStore);
}
if ($request->hasFile('avatar')) {
$user->avatar = $filenameToStore;
}
//Handle image Upload
if ($request->hasFile('image')) {
// Get filename with extention
$ImageNameWithExt = $request->file('image')->getClientOriginalName();
// Get just filename
$ImageName = pathinfo($ImageNameWithExt, PATHINFO_FILENAME);
// Get just Extention
$Extentions = $request->file('image')->getClientOriginalExtension();
// Filename to store
$ImageNameToStore = $ImageName.'_'.time().'.'.$Extentions;
// Upload Image
$paths = $request->file('image')->storeAs('public/images', $ImageNameToStore);
}
if ($request->hasFile('image')) {
$user->image = $ImageNameToStore;
}
$user->save();
$input = $request->except('password', 'password_confirmation');
if (!$request->filled('password')) {
$user->fill($input)->save();
return back()->with('success', 'Profile updated successfully!');
}
$user->password = bcrypt($request->password);
$user->fill($input)->save();
return back()->with('success', 'Profile and password updated successfully');
}
The image input field in edit.blade
<div class="form-group col-md">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input" id="customFile" >
<label class="custom-file-label text-align-left" style="text-align:left;"
for="customFile">Choose file</label>
</div>
</div>
I suggest you to change this :
$input = $request->except('password', 'password_confirmation');
to,
$input = $request->except('password', 'password_confirmation','image','avatar');
if ($request->hasFile('image')) {
$input['image'] = $ImageNameToStore;
}
if ($request->hasFile('avatar')) {
$input['avatar'] = $filenameToStore;
}
When using fill or update to persist Request data, it's always better to exclude the image fields. For any uploaded images in the request data it doesn't make much sense to store raw image data in database.
Rather the image can be stored on either local disk or something like S3 and the path to the saved image should be stored in database corresponding to the image field like avatar

Problem uploading images. I am using Laravel + Vue + vuetify

I have a code where I want to save images using Vue and Laravel saves the route in the database
The Controller:
public function update(Request $request, $id){
$home = Home::findOrFail($id);
$home->background = $request->background;
$home->title = $request->title;
$home->subtitle = $request->subtitle;
$home->icon_go = $request->icon_go;
$fileName = $request->image;
$path = $_SERVER['DOCUMENT_ROOT'].'assets/images/'.$fileName;
$home->image = $path;
$home->update();
file_put_contents($path, $fileName);
return response()->json([
'status'=> 200,
'title' => 'Home Update',
'data' => $home,
]);
}
The input:
<v-col cols="12" sm="12" md="12">
<input type="file"
#change="getImage"
label="Imagen"
required
:class="{ 'is-invalid' : form.errors.has('image') }">
<has-error :form="form" field="image"></has-error>
</v-col>
Only I just put the input, the form is working fine
The function update:
update(){
//Update a resource
this.$Progress.start()
this.form.busy = true;
this.form.image = this.form.image.name
this.form.put('/api/v1/home/' + this.form.id)
.then(response => {
this.getHome()
if (this.form.successful) {
this.$Progress.finish()
this.updateNotify()
}else{
this.$Progress.fail()
this.$snotify.error('¡Ha ocurrido un error!', 'Error')
}
})
.catch(e => {
this.$Progress.fail()
console.log(e)
})
},
The problem may be in the controller but I cannot detect it.
I'd appreciate your help.
The only thing that does not work is that the image is not showing the content
The photo is saved in the folder public / assets / images This is how the image is saved in the folder
Try using the below code. Since $request->image won't give file object. Instead, we need to use file() helpr.
public function update(Request $request, $id){
$home = Home::findOrFail($id);
$home->background = $request->background;
$home->title = $request->title;
$home->subtitle = $request->subtitle;
$home->icon_go = $request->icon_go;
$file = $request->file('image'); //gets the image file
$path = $_SERVER['DOCUMENT_ROOT'].'assets/images/';
$home->image = $path.$file->getClientOriginalName();
$home->update();
$file->move($path, $file->getClientOriginalName()); //stores in location
return response()->json([
'status'=> 200,
'title' => 'Home Update',
'data' => $home,
]);
}

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

I am trying to upload multiple images in laravel and facing issues as the same image is uploaded each time?

The problem is that my loop only running and uploading the same first pic each time rather than uploading each other in a row one after one!
Here is my code of the form
{!! Form::file('photos[]', ['roles' => 'form', 'class' => 'form-control-file','multiple' => true]) !!}
Here is my code of the controller
$files=$request->file('photos');
foreach ($files as $file) {
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$file->getClientOriginalExtension();
$insert->Save();
$uid = $insert->id;
$file->move($destinationPath,$imageName);
$image = array(
'youth_fashion_images_img' => $imageName
);
Images::where('youth_fashion_images_id',$uid)->update($image);
}
return redirect('adminpanel/viewimages');
Try this code :
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$imageName = 'uploads/products/'.time().'.'.$image->getClientOriginalExtension();
$image->move($destinationPath,$imageName);
$insert = new Images;
$insert->youth_fashion_images_category = $request->selectproduct;
$insert->youth_fashion_images_img = $imageName;
$insert->Save();
}
}
You should try this code.
if($request->hasfile('photos')) {
foreach($request->file('photos') as $image)
{
$destinationPath = 'uploads/products';
$name = 'uploads/products/'.time().'.'.$image->getClientOriginalName();
$image->move($destinationPath, $name);
$data[] = $name;
}
}
$insert= new Images;
$insert->youth_fashion_images_img = json_encode($data);
$insert->save();
json_encode to insert the multiple image names in one row.
So add $name in array $data[] = $name;.
I hope this will helps.

Resources