I've tried uploaded an image, but the only thing that is saved is picture inside the local folder. I've tried many ways such as using the save method, but everything is not working for me.
It's appearing blank in the database table. When I dd($request0>all()), the name of the file did appeared, but after I dd($funds). Somehow the image attribute is gone.
Controller
public function store(Request $request)
{
// Validate funds form data
$validated = $request->validate([
'title' => 'required|string|unique:funds|min:5|max:100',
'content' => 'required|string|min:5|max:2000',
'image' => 'required|image|max:2048',
]);
$filename = $request->image->getClientOriginalName();
$validated['image'] = $request->image->storeAs('images', $filename, 'public');
// Create slug from title
$validated['slug'] = Str::slug($validated['title'], '-');
// Create and save funds with validated data
$funds = Fund::create($validated);
// Redirect the user to the created funds with a success notification
return redirect(route('funds.index', [$funds->slug]))->with('success', 'Post created!');
}
Blade
<form method="post" action="{{ route('funds.store') }}" enctype="multipart/form-data">
#csrf
#include('partials.errors')
<div class="field">
<label class="label">Image</label>
<div class="control">
<div class="col-md-6 mx-auto">
<img src="#" alt="image" id="img"
style="max-width:150px; display: block; margin-left: auto; margin-right: auto; padding-bottom: 10px; width: 60%;">
<input type="file" id="upload" name="image">
</div>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link is-
outlined">Publish</button>
</div>
</div>
</form>
Unless the table's column that's supposed to store the image is of the binary data type, it'll never show up in the database.
You didn't show your table's schema, so I can only guess here. If the image is being uploaded and stored to your storage directory, I recommend you save the file path to the database after it's done uploading (it's a string). Alternatively, you could just base64_encode the image and store it on that column, so that it can be displayed with an <img> element later.
Have a look at this part of the official documentation.
$path = Storage::disk('public')->put($fileName, $path);
Then save the $path value in database for the imagePath field.
You can specify drive. Public is the one accessible to all users once you run php artisan storage:link command in your terminal. Local disk is everything in private "/storage/app/private/.....".
Also for the slugs have a look at at this package. It will generate slugs automatically if you install and configure it properly in your specific models.
Related
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()]);
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
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]);
I'm working on the database restore menu for an application I created, I'm using sqlite for my database, and I want to put my previously backed up database file to the database directory
backupAndRestore.blade.php
<form method="POST" action="/admin/backupAndRestore/restore" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="file-field input-field">
<div class="btn">
<span><i class="material-icons">file_upload</i></span>
<input type="file" name="database" accept=".sqlite">
</div>
<div class="file-path-wrapper">
<input type="text" class="file-path" placeholder="Example: file_name.sqlite" readonly>
</div>
</div>
<button type="submit" class="btn">restore</button>
</form>
web.php
Route::post('/admin/backupAndRestore/restore', 'DatabaseController#restore');
DatabaseController.php
public function restore(Request $request)
{
$database = $request->database;
$file_name = 'database2.sqlite';
$path = database_path($file_name);
file_put_contents($path, $database);
return $path;
}
my code works, the file is stored in the database directory, the problem is when I backup my database file size is 22kb, but when I restore it and I check the database directory, the file is 1kb size and when I open using sublime file contents as shown below
Images
which I expect as shown below
Images
can someone tell where my fault is?
You are using file_put_contents which inserts the contents in the given file and does not move the file.
If you want to store a file in database path..
public function restore(Request $request)
{
$this->validate($request, [
'database' => 'required|file|mimes:sqlite'
]);
$databaseFile = $request->database;
$fileName = 'database2.sqlite';
$databaseFile->move(database_path(), $fileName);
// return success message...
}
For more information uploading files: https://laravel.com/docs/5.4/requests#files.
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') }}" ...>