$request->hasFile() returns false when uploading - php

I can't seem to get my app to upload a file when submitting a request in my Laravel 5.8 application. No matter what type of file I upload, hasFile() always returns false.
Form
<form action="{{ route('items.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group py-50">
<input type="file" name="featured_img" value="featured_img" id="featured_img">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Upload Image" name="submit">
</div>
</form>
Controller
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//Check if image has been uploaded
if($request->hasFile('featured_img')){
return "True!";
} else {
return "False!";
}
}
dd() Output
array:7 [▼
"_token" => "sREFSO8bs0rWil05AESVrwEl37XtKOJAF2nCkTNR"
"status" => "published"
"featured_img" => "example.jpg"
"submit" => "Upload Image"
]
enctype="multipart/form-data" has been included in my form.
I have tested multiple files which are around 50-80 KB in size
I am running another Laravel app in the same environment without any issues. I also tested uploading the same images to that app without any problems. This leads me to believe this has nothing to do with misconfiguration of php.ini
dd($request->all()); returns a string name for "featured_img" instead of file object
UPDATE
While Making changes to my view I did not realize I had two form actions in place with the same route. Stupid me. Thank you for everyone that helped me troubleshoot.

check try some case:
check max file size upload in php.ini
check exist enctype="multipart/form-data" in tag or not.
check method in tag (must use POST method), and route in Web.php must have post route

I tested in one of my installation with
in web.php
use Illuminate\Http\Request;
Route::get('test', function(){
return view('test');
});
Route::post('test', function(Request $request){
dd($request->hasFile('test'));
})->name('test');
in test.blade.php
<form action="{{ route('test') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group py-50">
<input type="file" name="test" id="featured_img">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Upload Image" name="submit">
</div>
</form>
$request->hasFile('test') returns true, please check with this code in your controller or route file and let me know, if you are getting any issue.
Also
You should use #stack to add script to your blade and not #section
Update
According to your updated view page code, you have two form in your view posting to same route check that and first form is not closed and second is open.

Related

simple input type file not getting the file

Hi im new to laravel 9 and im trying to upload file from view to controller, but somehow the input file didnt pass the file to controller.
im using laravel 9 with boostrap in it.
heres my code :
view
<form enctype="multipart/form-data" action="{{ route('profile.put') }}" method="POST">
#csrf
#method('POST')
<div class="card-body">
<input id="file" name="file" type="file">
<button type="submit" class="btn btn-block btn-primary">{{ __('Save') }}</button>
</div>
</form>
controller
public function put(Request $request){
return $request;
}
i try to see the $request variable but the result is like this
enter image description here
i try the solution like add enctype="multipart/form-data" but still didnt work.
thank you in advance
I think you simply should get the request by its name or using `$request->all()`, you can do these two things:
In your controller you should write your put method like below:
public function put(Request $request){
$file = '';
if($request->file('file'))
{
$file = $request->get('file);
}
return $file;
}
or you can use the below code in your put method
public function put(Request $request){
return $request->all();
}
Note: If you don't send the file as a JSON Response you should return it to view after saving operation;
and also, there is no need to put #method('POST') inside the form;

error: The POST method is not supported for this route. Supported methods: GET, HEAD. - using laravel livewire

I'm trying to do an image upload using Laravel livewire, but when I click on the button "upload" to test the functionality this error appears
The POST method is not supported for this route. Supported methods: GET, HEAD'
The programs:
ROUTE
Route::get('/upload', UploadFoto::class)->name('upload.foto.user');
CONTROLLER (using dd for the tests)
<?php
namespace App\Http\Livewire\User;
use Livewire\Component;
class UploadFoto extends Component
{
public $foto;
public function render()
{
return view('livewire.user.upload-foto');
}
public function storageFoto()
{
dd('aqui');
}
}
VIEW
#extends('layouts.app')
#section('content')
<div>
{{-- To attain knowledge, add things every day; To attain wisdom, subtract things every day. --}}
<form action="#" method="post">
<input type="file" name="foto" id="foto" wire:submit.prevent="storageFoto">
<button type="submit">Upload</button>
</form>
</div>
#endsection
You set get method on this route - but upload use post method. Change it:
Route::post('/upload', UploadFoto::class)->name('upload.foto.user');
please check this, you added submit in wrong place of form
<div>
<form wire:submit.prevent="storageFoto" method="post">
<input type="file" name="foto" id="foto">
<button type="submit">Upload</button>
</form>
</div>
and you should check this lines into app file
#livewireStyles
#livewireScripts
change route method to Post
Route::post('/upload', UploadFoto::class)->name('upload.foto.user');

The POST method is not supported for this route. Supported methods: GET, HEAD upload image

i want to insert link of an image into a field in the database like annonces\August2020\image.jpg in storage, but it gives me error:The POST method is not supported for this route. Supported methods: GET, HEAD.
file.blade.php
<form action="/file" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="file" id="file" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
web.php
Route::get('file', 'fileController#index');
Route::get('save', 'fileController#save');
FileController.php
public function save()
{
request()->validate(['file' => 'required|mimes:doc,docx,pdf,txt|max:2048',]);
if ($files = $request->file('fileUpload')) {
$destinationPath = 'public/file/'; // upload path
$profilefile = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profilefile);
$insert['file'] = "$profilefile";
}
$check = Document::insertGetId($insert);
return Redirect::to("file")
->withSuccess('Great! file has been successfully uploaded.');
}
as the error said, you need to declare the route as POST
Route::post('save', 'fileController#save');
Also, put the correct route into the form action attribute
<form action="/save" method="post" enctype="multipart/form-data">
you are using post method in the form and then in the web.php you are using get method which is wrong.
in We.php use something like below:
Route::post('save', 'fileController#save');
Also please change the action attribute value to save which is a url in web.php because you are calling save method in the Controller
<form action="/save" method="post" enctype="multipart/form-data">

Trying to submit one <form> with method="POST" duplicates the route and doesn't save the information with an store function()

Im trying to submit one form with method post to save one element in astore function() but when I click submit duplicates the route, for example looking like this:entradas/1/ventaEntrada/200000/montoTotal/entradas/1/ventaEntrada/200000/montoTotal and doesn't save the information, I dont know why this is happening
Below i will let the code of my route,my form,my create function() and my store function()
Also show404 Not Found when I click submit
Route
Route::resource('/entradas/{id_entrada}/ventaEntrada/{precio_entrada}/montoTotal', 'Venta_entradaController');
create function()
public function create(Request $request,$id_entrada,$precio_entrada){
$venta_entrada = DB::select(DB::raw(
"SELECT monto_total,fecha,fk_cliente_natural,fk_cliente_juridico
FROM venta_entrada "
)
);
return view('home.crearVenta_entrada')
->with('venta_entrada',$venta_entrada)
->with('id_entrada',$id_entrada)->with('precio_entrada',$precio_entrada);
}
store function()
public function store(Request $request,$id_entrada,$precio_entrada)
{
$venta_entrada=new Venta_entrada();
$venta_entrada->monto_total=$precio_entrada+$request->monto_total;
$now = new \DateTime();
$venta_entrada->fecha=$now->format('d-m-Y');
$venta_entrada->fk_cliente_natural=1;
$venta_entrada->save();
return back();
}
Form with the method POST
<form action="entradas/{{$id_entrada}}/ventaEntrada/{{$precio_entrada}}/montoTotal" method="POST">
#csrf
<input type="number" name="monto_total" placeholder="Monto total" class="form-control mb-2" required>
<button clas="btn btn-primary btn-block" type="submit">ADD</button>
BACK
</form>
I have check your problem and you have use "Resource Route" right.
so for routing run following command in your terminal/command prompt
php artisan route:list
It will show all routes lists and find your action name
Then you'll add in form action name like
<form action="{{ route('name') }}" method="post">
...
</form>
Example:
<form action="{{ route('Venta_entrada.store') }}" method="post">
...
</form>
I hope it will help you :)

Using Mimes for Validating Laravel File Post - Word File

I have a form that I post file. I am trying to use validation to accept only word documents. I tried using mime types however doesn't seem to work and I couldn't spot my mistake.
<form action="" method="post">
<div class="form-group{{ $errors->has('myFile') ? ' has-error' : '' }}">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="file" id="myFile" name="myFile">
<label for="myFile">MyFile</label>
#if ($errors->has('myFile'))
<div {{ $errors->first('myFile') }}</div>
#endif
</div>
</div>
</div>
</form>
This posts successfully and I receive it in my controller.
In my controller, I try to validate it, however it is always returning the error, even though the file is in '.doc' format.
public function myController(Request $request) {
$validator = MyValidations::myFormValidator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
...
}
and the validator:
public static function myFormValidator($data) {
return Validator::make($data, [
'myFile' => 'required|mimes:application/msword'
// I also tried
// 'myFile' => 'required|mimes:doc,docx'
]);
}
Edit: I have seen some posts on SO, regarding that there is a file config > mimes.php but I don't have it on Laravel 5.3
Actually, there is nothing really wrong with your validation code. The problem is that your form is not submitting the files properly.
Add the proper enctype to your form like so:
<form action="" method="post" enctype="multipart/form-data">
Also make sure to get the syntax right for validation (but I think you knew this part). Use either of these two:
'myFile' => 'required|mimes:doc,docx'
'myFile' => 'required|mimetypes:application/msword'
Try this:
'myFile': 'required|mimes:doc,docx'

Categories