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

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,
]);
}

Related

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

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.

Laravel: how can i get files from database in edit form. so i dont have to reupload if i dont want to change the files

blade edit
<form action="/files" method="POST" enctype="multipart/form-data">
{{csrf_field()}}
<label for="dokumen">Dokumen Awal : ({{$aktivitas_list->dokumen}}) <br><i>Upload Ulang Dokumen</i></label>
<input type="file" id="dokumen" name="dokumen" accept=".pdf" class="form-control" value="{{$aktivitas_list->dokumen}}">
#if ($errors->has('dokumen'))
<span class="text-danger">{{ $errors->first('dokumen') }}</span>
#endif
controller store
$aktivitas_list = new Aktivitas;
$aktivitas_list->pt_id = $request->get('pt_id');
$aktivitas_list->nama_aktivitas = $request->get('nama_aktivitas');
$aktivitas_list->tgl_aktivitas = $request->get('tgl_aktivitas');
$aktivitas_list->tempat = $request->get('tempat');
$aktivitas_list->jenis_aktivitas = $request->get('jenis_aktivitas');
$aktivitas_list->dokumen = $request->file('dokumen');
$aktivitas_list->tenggat_waktu = $request->get('tenggat_waktu');
$aktivitas_list->deskripsi = $request->get('deskripsi');
$aktivitas_list->status = $request->get('status');
$aktivitas_list->user = $request->get('user');
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}
controller update
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'required|mimes:pdf'
);
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
The problem is, if I don't select again the file when I update the data so the data is null. for example i just want to edit field nama aktivitas and not change the files. and another example i want to update all field. how can i get the files beside the browse button? how can i solve them? please guys help me
In Controller on update method
Make file as optional.
Check if request has file then make process of upload.
in view you can't set file input value for security reason.
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'nullable|mimes:pdf'//make file as optional
);
if($request->file('dokumen')){//check if file are exists on request
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
you can check if file existed then upload it and save file's new name in database and if file didn't exist just escape this field so old value remain in database.
if($request->hasFile()) {
}
See docs here
public function update(Request $request)
{
$rules = array(
'nama_aktivitas' => 'required',
'dokumen' => 'sometimes|mimes:pdf'
);
//Validation of request data
if($request->hasFile('dokumen') && $request->file('dokumen')->isValid()){
$dokumen = $request->file('dokumen');
$tujuan_upload = 'document-upload';
$dokumen->move($tujuan_upload, $dokumen->getClientOriginalName());
//Since your provided code snippet for update is truncated
// don't know how $aktivitas_list is instantiated
$aktivitas_list->dokumen = $dokumen->getClientOriginalName();
}
$aktivitas_list->status = $status=1;
$aktivitas_list->user = Auth::user()->name;
$user = Auth::user()->name;
if ($aktivitas_list->save()) {
return redirect('pt')->with('success', 'Data Berhasil Ditambahkan');
} else {
return redirect('pt')->with('error', 'error message');
}
}

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

Display name instead of id in url laravel

I would just like to ask how do I display the name of the business instead of it's id.
It's currently displayed like this, localhost:8000/1/Belen'sChoice and desired output is
localhost:8000/Belen'sChoice. I can get the name however it says 'trying to find id'.
Controller
public function show($id)
{
$categories = Category::all();
$businesses = Business::find($id);
if (Auth::check()) {
$userId = Auth::user()->id;
$users = User::where('id', $userId)->get();
$posts = Post::where('business_id', $businesses->id)->get()->sortByDesc('created_at');
$supporters = Supporter::where('user_id', $userId)->get();
$photos = Image::where('business_id', $businesses->id)->get();
$albums = Album::where('business_id', $businesses->id)->get();
$count = 0;
if ($businesses->user_id != Auth::user()->id) {
$businesses->views = $businesses->views + 1;
$businesses->save();
} else {
$businesses->views = $businesses->views;
}
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
'users' => $users,
'posts' => $posts,
'supporters' => $supporters,
'count' => $count,
'images' => $photos,
'albums' => $albums,
]);
} else {
return view('businesses.index', [
'categories' => $categories,
'businesses' => $businesses,
]);
}
}
Blade
<a class="text-center" href='{{ url("/businessprofile/".$business->id."/".str_replace(" ", "" ,$business->name)) }}'><img class="bprof-img" src='{{ asset("storage/$business->logo") }}'>{{ $business->name }}</a>
Web.php
Route::get('/businessprofile/{id?}/{name}', 'BusinessController#show');
TIA
take one Column in your business migration
$table->string('slug')->unique();
and save it like this way in your controller
//use this at the bottom of your controller
use Illuminate\Support\Str;
$business = new Business;
$business->slug = Str::slug($request->name) // whatever you request dring //creating a business row
//and after that save it
$business->save();
then in your controller find the row using slug
public function show($slug)
{
$business = Business::where('slug',$slug)->first();
//and rest of your operation
}
href='{{ url("/".str_replace(" ", "" ,$business->slug))}}'
then in your web
Route::get('/{slug}', 'BusinessController#show');

Laravel error with upload dropzone

I have this code:
public function getUpload()
{
return View::make('foto/upload');
}
public function postUpload()
{
$file = Input::file('file');
$filename = $file->getClientOrginalName();
$path = 'uploads';
return $file->move($path, $filename);
}
Here views:
{{Form::open(array('url' => 'foto/upload', 'class' => 'dropzone'))}}
{{Form::close()}}
After upload, display 'X', but how I can display this error? Or what I should fix?
You got a typo. It is "getClientOrIginalName"

Resources