I am new to Laravel 5. Actually I'm using Laravel Framework version 5.1.16. When uploading an image, it is uploading and saved in database table, but it is not moved to a specified folder.
Any help would be appreciated.
This is my controller code:
public function addexpense(Request $request) {
$inputs=Input::all();
$validation = Validator::make($inputs, Expense::$rules);
if($validation->fails()) {
return Redirect::to('expenseaddform')->withErrors($validation)->withInput();
}else{
$input=Input::only('id','expense_date','expense_category_id','vendor_id','customer_id','amount','tax1_id','tax2_id','note','receipt');
$data->expense_date = $input['expense_date'];
$data->expense_category_id = $input['expense_category_id'];
$data->vendor_id = $input['vendor_id'];
$data->customer_id = $input['customer_id'];
$data->amount = $input['amount'];
$data->tax1_id = $input['tax1_id'];
$data->tax2_id = $input['tax2_id'];
$data->note = $input['note'];
$image = Input::file('receipt');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(468, 249)->save('public/uploas/'. $filename);
$data->receipt = $input['image'];
$data->save();
return redirect('expenseinfo');
}
}
Form code:
<form action="addexpense" enctype="multipart/form-data" >
Receipt:</td><td><input type="file" name="receipt"value="{{Input::old('receipt')}}">
<input style="margin-left:30px"type="submit" value="Add" name="submit">
</form>
You are doing it wrong with Image::make() function. Try the following:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path() . '/uploads/' . $filename);
Try this:
Image::make($image->getRealPath())->resize(468, 249)->save(public_path('uploads/'). $filename);
For more information you can check the below link:
https://youtu.be/F92JpVWhDw4
Related
I would like to display an employee picture using the url as shown below which I think should work but not. However it does work with the second url which is static. why is this happening?
This the first url that does not work
<img id="message" src="{{url('/profile_picture/' . $employee->picture)}}" style="width: 150px;"/>
This is the second url that does work
<img id="message" src="{{url('/profile_picture/20220615232745.jpg')}}" style="width: 150px;"/>
To save a picture I use the following method
public function ProfileStore(Request $request)
{
$data = User::find(Auth::user()->id);
$data->name =$request->name;
$data->email =$request->email;
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = " $filename";
}
$data->save();
return redirect()->route('profile.index');
}
The route
Route::post('/people/employees/profiles/store', [ProfileController::class, 'ProfileStore'])->name('profile.store');
Route::get('/people/employees/profiles/edit/{id}', [ProfileController::class, 'ProfileEdit'])->name('profile.edit');
My edit method
public function ProfileEdit()
{
$id = Auth::user()->id;
$employee = User::find($id);
return view('fms.people.employee.profiles.profile_edit')->with('employee',$employee);
}
in you profilestore function, when setting the $filename to $data['picture'], you have extra space before it.Remove that space and try again. For ex:
if ($request->file('picture')) {
$file = $request->file('picture');
$filename = date('YmdHis') . "." . $file->getClientOriginalExtension();
$file->move('profile_picture/', $filename);
$data['picture'] = "$filename";
}
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
I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}
I cannot seem to upload an image file with Laravel. I keep getting the photo failed to upload.
My form:
<form id="save_report_form" action="{{ route('report.add') }}" method="post" enctype="multipart/form-data">
<input type="file" name="image" class="upload-photo" id="image" accept="image/png,image/jpg" />
</form>
My Controller:
public function add(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:png,jpg',
]);
// Get all file details and store in public
$disk = Storage::disk('public');
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$filename = $file . '.' . $ext;
$disk->put($filename, file_get_contents($file), 'public');
return redirect()->back();
}
I have changed upload_max_filesize to 20mb for my dev server.
Where can I look to find the reason for the upload failure? I am not getting anything in the Laravel log. What have I missed. Thanks.
can you replace
$filename = $file . '.' . $ext;
with
$filename = $request->image->getClientOriginalName();
You can check what is the result of $filename with dd() /dd($filename) function and see if it is what you expect. If it is not, probably there is the problem.
Also as far as i see in the official docs(https://laravel.com/docs/5.8/filesystem#file-visibility) the usage of put() method is exampled without php native file_get_contents(check this also).
I'm building a gallery with multiple files functionality.
So far I'm having two issues, but let's paste my code first.
Controller:
public function store(Request $request)
{
$gallery = new GalleryImage();
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
}
}
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
return back()->with('success_message','Images has been uploaded!');
}
View blade:
<form action="{{ route('gallery-images.store') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<input type="hidden" name="gallery_id" value="{{ $gallery->id }}">
<input type="file" name="image[]" id="id_imageGallery" class="form-control" multiple="multiple" required>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>
My first issue when I have my code like this and upload three files, it's successfully storing the files into /uploads/temp directory, but in my database I can see there's only one image uploaded, instead of three.
My second issue is when I change my code and use the commented part (because I want to store those three images into Storage):
$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
I'm getting this error:
Call to a member function storeAs() on array
How can I upload those multiple images into the Storage folder and record them all into the database?
-- EDIT --
I've solved my first issue!
I've simply put the save method and other details inside the loop. I've should have thought about this before :)
Here's my updated code:
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery->image = $image->move(public_path().'/uploads/temp/', $name);
//$gallery->image = $request->file('image')->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}
Now only thing to do is how to store them into File Storage, instead of the public_path and avoid that error:
Call to a member function storeAs() on array
I've finally solved the issues and I'm posting it, so it may be useful for some.
Here's my code:
public function store(Request $request)
{
if($request->hasFile('image')) {
foreach($request->image as $image) {
$path = $image->getClientOriginalName();
$name = time() . '-' . $path;
$gallery = new GalleryImage();
$gallery->image = $image->storeAs('public/gallery-images', $name);
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','The images have been uploaded!');
}
Try to implement using the following code, it will give uploaded files url in serialized format
public static function upload_file($file){
$file_name = time();
$file_name .= rand();
$file_name = sha1($file_name);
if ($file) {
$ext = $file->getClientOriginalExtension();
$file->move(public_path() . "/uploads", $file_name . "." . $ext);
$local_url = $file_name . "." . $ext;
$s3_url = url('/').'/uploads/'.$local_url;
return $s3_url;
}
return "";
}
public static function upload_multiple_files($files){
if(is_array($files)){
$return_array = array();
foreach ($files as $file){
if(!empty($file)){
$return_array[] = self::upload_file($file);
}else{
$return_array[] = '';
}
}
return serialize($return_array);
}else{
return NULL;
}
}
//I have updated and commented your code. Try it, It should work.
public function store(Request $request)
{
if($request->hasFile('image')) {
$images = $request->file('image');
foreach($images as $image) {
$gallery = new GalleryImage();
// laravel auto manages unique name and extension of file.
$gallery->image = $image->store('gallery-images', 'public');
$gallery->gallery_id = $request->gallery_id;
$gallery->save();
}
}
return back()->with('success_message','Images has been uploaded!');
}