VIEW PDF 404 LARAVEL 7 - php

I want to have a button where a client can view an applicant's document that the candidate has uploaded, but for some reason I cannot figure out why it doesn't work.
It was working fine offline, but I deployed the site via FTP today and It doesn't want to work.
I am less than a junior developer so please be kind about messy code,
Here is my code for
upload blade:
<form action="{{route('cv')}}" method="POST" enctype="multipart/form-data">#csrf
<div class="card">
<div class="card-header">Update CV</div>
<div class="card-body">
<input type="file" class="form-control" name="cv"><br>
<button class="btn btn-success float-right"
type="submit">Update</button>
#if($errors->has('cv'))
<div class="error" style="color: red;">{{$errors->first('cv')}}</div>
#endif
</div>
</div>
Code for route:
Route::post('user/cv','UserController#cv')->name('cv');
Code for Controller:
public function cv(Request $request){
$user_id = auth()->user()->id;
$cv = $request->file('cv')->store(public_path('storage/files'));
Profile::where('user_id',$user_id)->update(['cv'=>$request->file('cv')->getClientOriginalName()]);
return redirect()->back()->with('message', 'CV Successfully Updated!');
}
Code for viewing the CV :
View my CV
When I click the button I get this url:
cvroad.co.za/storage/Kevin%20Breed.pdf
The name of the file is : Kevin Breed.pdf and that is how it is seen in my database aswell.
but still 404 not found?
Any and all help would be appreciated, thank you!

Instead of hard-coding the file path, use Laravel's storage_path() to get to the right path.
$cv = $request->file('cv')->store(storage_path('files'));
Though if you're using Storage::url(), then it's looking in public/storage, so the proper way to go about it might to use the public_path
$cv = $request->file('cv')->store(public_path('storage/files'));
Also when saving to the database, you're saving the full path, not just the name. You can store just the name like this:
Profile::where('user_id',$user_id)->update(['cv'=>$request->file('cv')->getClientOriginalName()]);

Related

Can't edit the database, Laravel

I have an edit form with a text field and an image field where a user can edit and upload new text or a image if he/she wants to. But if the user does not upload a new image I just want to keep the old image in the database.
My Problem
The problem is when I hit upload button, I'm redirected to the article page and no error is shown but the DB has not been updated what so ever.
Any help would be appreciated as I have tried multiple methods with no success.
Thank you in advance.
web.php
Route::get('/tests/edit/{id}', 'TestController#edit');
Route::patch('/tests', 'TestController#update');
TestController.php
public function edit(Request $request)
{
$test = Test::findOrFail($request->id);
return view('test.edit', ['test' => $test]);
}
public function update(Request $request, Test $test)
{
$test->user_id = $request->user()->id;
$test->name = $request->name;
if($request->hasFile('image')) {
Storage::delete('public/image/' . $test->image); //Delete old image
$path = $request->file('image')->store('public/image');
$test->image = basename($path);
}
$test->update();
return redirect('/tests')
}
edit.blade.php
#extends('layouts.app')
#section('content')
<div>
<form action="/tests" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('patch') }}
name:<input type="text" name="name" value='{{ $test->name }}'><br>
image: <input type="file" name="image"><br>
<input type='submit' value='upload'>
</form>
</div>
#endsection
edit.blade.php add this :
<input type="hidden" name="id" value="{{ $test->id }}">
TestController.php
use $test->save(); instead of $test->update();
I had the same problem as you.I work on a ordering website with laravel that you can get data from laravel and show it to user and also he can order something from the website and the database will be updated.But, I cannot neither get or update data in database.I work with wampserver, mysql and the problem is solved once I switched to MariaDB instead of mysql in phpmyadmin: http://localhost/phpmyadmin/

PHP - Laravel: Getting a 403 forbidden error when trying to save javascript code to mysql database

I know that this is generally frowned upon, but for my specific reasons which I'll state below, I need this functionality:
So what we're doing on this website is that we are allowing users to buy "stores" on which they can sell products, and now those users want to add stuff like "Facebook Pixel" to their stores to allow them to track different activities.
Here's my form responsible for the code
<form action="{{ url('vendor/store/settings/analytics/update') }}" method="POST" style="margin-top: 30px;">
{{ csrf_field() }}
<div class="analytics-form">
<div class="col-md-8 col-md-offset-2 analytics-box">
<div class="form-group">
<label for="">Please pick a type of analytics to install:</label>
<select name="analytic_type[]" id="" class="form-control">
#foreach($analytic_types as $type)
<option value="{{ $type }}">{{ ucwords(str_replace('_', ' ', $type)) }}</option>
#endforeach
</select>
<br>
</div>
<div class="form-group">
<label for="">Please type/paste the code for this analytic:</label>
<textarea class="form-control" cols="5" rows="5" name="analytic_code[]" required></textarea>
<br>
</div>
</div>
</div>
<button class="btn btn-primary btn-block" id="applyAnalytics" type="submit" {{ $store->vendor->hasAnalytics() ? '' : 'disabled'}}>Apply Changes</button>
</form>
And here's the controller method I want to "hit":
public function updateAnalytics(Request $request)
{
try {
$store = auth()->user()->store;
auth()->user()->analytics()->delete();
if($request->has('analytic_type')) {
foreach($request->analytic_type as $index => $value) {
Analytics::create([
'user_id' => auth()->user()->id,
'analyticable_id' => $store->id,
'analyticable_type' => get_class($store),
'method_type' => $request->analytic_type[$index],
'method_code' => $request->analytic_code[$index],
]);
}
}
flash(__("Common.Saved_Successfully"));
} catch (\Exception $e) {
session()->flash('title', __("Common.Error"));
session()->flash('message', __("Common.An_Error_Happened"));
session()->flash('message-class', "error");
}
return redirect()->back();
}
This method works fine locally if I enter either normal text or code into the textarea, but if I tried to enter & submit the below block of code everything blows up, this block of code is the one provided by Facebook Pixel to its users, which I want to save in my database:
<!-- Facebook Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '339673053324500');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=339673053324500&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->
If I put the above code into the text area and submit the data to the server, I get this error below:
Forbidden
You don't have permission to access /app/public/vendor/store/settings/analytics/update on this server.
Additionally, a 403 Forbidden error was encountered while trying to
use an ErrorDocument to handle the request.
The server isn't even allowing me to hit the route in question, or any other route from this form as long as I am submitting code.
Note:
This is probably not an actual permission issue but a security related thing, because I've tried changing permissions on the server for all of the involved files from 0644 to 0755 and nothing changed, of course I might have done something wrong along the way, all suggestions are welcome.

checkbox values not being received in laravel controller

I have this bit of code in my form edit.blade.php :
#php
$imagepath="images/Service/".$services->name."/";
$images=glob($imagepath.'*.*');
#endphp
<div class="row">
#foreach($images as $image)
#php
$count++;
#endphp
<div class="col-md-5">
<img src="{{URL::asset($image)}}" style="height: 150px;object-fit: contain;">
</div>
<div class="col-md-1">
<input form="services" type="checkbox" name="deleteimagelink[]" value="{{($image)}}" >
</div>
#endforeach
</div>
This is for passing the path of those images meant to be deleted.
And I have this snippet in my controller:
print_r($request->input('deleteimagelink'));
$deletables=$request->input('deleteimagelink');
foreach ($deletables as $deletable)
{
print_r($deletable);
unlink($deletable);
}
I have this problem that nothing is being received in the $request->input('deleteimagelink') parameter.
Please guide me if I'm doing anything wrong.
If nothing seems weird, can you please guide me how to deal with these checkbox situations in laravel.
I consulted related answers from internet but nothing seems to work.
<form class="form-group" method="post" action="/destroy" enctype="multipart/form-data">
#csrf
<input type="checkbox" name="deleteimagelink[]" value="1" >
<input type="checkbox" name="deleteimagelink[]" value="2" >
<button class="btn btn-primary" type="submit">Actualizar</button
</form>
Controller
public function destroy(Request $request)
{
return $request;
}
{"_token":"BetJnyujXvJnpkkwDU31kYO7lVz5OqflMQDoCLQy","deleteimagelink":["1","2"]}
This Works for me!
I had included the code above outside the <form></form> tag in order to justify to my view. Interestingly, it didn't work even though that I had included form="services" as a parameter in my input field{services is the form name here}. I had worked something like this before and it had worked pretty good that time. I managed to get the <form></form> tags outside the whole of my form elements and it is working fine now.
Thank you everybody who tried to help.

homestead laravel 5 : link Download file from storage

i am need hint link to download upload file, currently i am following this answer
here is my code
Routes file :
Route::get('getDownload/{remind_letter}',
['as'=>'downloadData',
'uses'=>'DockController#getDownload']);
Controller File :
public function getDownload($remind_letter)
{
$download = Dock::where('remind_letter','=',$remind_letter)->firstOrFail();
$file =Storage::disk('local')->get($download->remind_letter);
return (new response($file))->header('Content-Type', $entry->m1);
}
result file
<div class="row">
<div class="form-group">
<div class="col-xs-5">
<label class="col-sm-7">Remind Letter :</label>
<input type="text" name="remind_letter" value="{{$getData->remind_letter}}">
</div>
<div><a href="{{ route('downloadData',$getData->remind_letter) }}">
<button class="btn btn-success btn-sm">Download</button></a></div>
</div>
</div>
and the result link dock.start/star/getDownload/home/vagrant/Code/dock/storage/app/25/JTK/2015/Renewal License Kaspersky/Moonarch Security/tmp/phpQaGzoD.pdf
but the link is always show up error 404 and i can't download file
FYI when upload file i am using storage_path() function
it fix, i am wrong logic, when upload file it should using getFilename() function, $entry->filename = $filename->getFilename().$extension;

Image upload using picEdit and symfony

I am trying to create a simple form that allows a user to upload a profile picture. To avoid having to deal with too much symfony code, I am using picEdit and I embedded the form directly to the appropriate twig template (which links to both picEdit .css and .js files, and jquery). This form is inside a boostrap modal dialog as seen below:
<div class="modal-dialog">
<div class="modal-content animated fadeIn">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<i class="fa fa-upload modal-icon"></i>
<h4 class="modal-title">Profile picture</h4>
<small>Use the options below to upload and edit your profile picture.</small>
</div>
<div class="modal-body" style="text-align: center">
<form action="upload.php" method="post" id="avatarUploadForm" name="avatarUploadForm" enctype="multipart/form-data">
<input type="file" name="avatarImage" id="avatarImage">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
<button type="submit" id="uploadButton" name="uploadButton" class="btn btn-primary">Upload Picture</button>
</form>
</div>
</div>
I also added the following java script function to the template:
<script type="text/javascript">
$(function() {
$('#avatarImage').picEdit();
});
</script>
The form action points to upload.php, shown below (in its simplistic form) and stored in web/upload.php:
<?php
if (isset($_POST['uploadButton'])){
$file = $_FILES['avatarImage']['name'];
move_uploaded_file($file,"/avatars/$file");
}
?>
When I hit the Upload Picture button, I get a success notification as seen below, but the file does not show up in the directory to where it is being sent, and I suspect the upload.php script never really gets triggered. Any suggestions on what I may be doing incorrectly?? *Disclaimer: I'm very new to php/symfony/java script
You are using the wrong key to move. Change upload.php to:
if (isset($_POST['uploadButton'])){
$file = $_FILES['avatarImage']['tmp_name'];
$fileName = $_FILES['avatarImage']['name'];
if(move_uploaded_file($file,"/assets/img/$fileName")){
header('Content-Type','application/json');
echo json_encode(array(
'status' => 'success'
));
}
else{
header('Content-Type','application/json');
echo json_encode(array(
'status' => 'failed'
));
}
}
http://php.net/manual/en/function.move-uploaded-file.php
You should also not rely on the file name of the uploaded file, its a potential for injection. Use some other naming schema or run the name through a scrubber.
Using this particular plugin im also not sure how you plan to tie the image back to the user entity. This plugin seems to only handle upload.
Make sure that you are not getting errors when uploading the file:
$('#image').picEdit({
formSubmitted: function(response){
console.log(response);
}
});
Symfony Approach
Use a form and controller. This will give you access to a lot more and save you a step in updating the users profile image.
We are going to make a few assumptions. First that only the logged in user will be changing their profile. Second that all directories have the proper permissions. And lastly that you are using annotations for routing
//ProfileController
...
/**
* #Route('/upload-profile-image', name="upload_profile_image")
* #Method({"POST"})
*/
public function uploadProfilePictureAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('UserBundle:User')->findOneById($this->getUser()->getId());
$form = $this->createFormBuilder($user)
->add('avatarImage','file')
->getForm();
$form->handleRequest($request);
if($form->isValid()){
$user->upload();
$em->flush();
return new JsonResponse(array(
'status'=>'success'
));
}
return new JsonResponse(array(
'status' => 'failed',
'message' => $form->getErrors(true)
));
}
Then make sure that you have your user entity setup with the proper functions described here: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
Then just change your form to:
<form action="{{ path('upload_profile_image') }}" ...>

Categories