Using Mimes for Validating Laravel File Post - Word File - php

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'

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;

When Use PUT or PATCH For Updating Data

I want to edit some information which is retrieved from the DB, at the edit.blade.php:
<form action="{{ route('updateWallet', ['id'=>$wallet->id]) }}" method="POST" enctype="multipart/form-data">
#csrf
<label for="title" class="control-label">Title</label>
<input type="text" id="title-shop" name="title" class="form-control" value="{{ $wallet->title }}" autofocus>
<input class="form-check-input" type="checkbox" name="cachable" value="cashable" id="cacheStatus" #php if(($wallet->is_cachable) == 1) {echo 'checked';} #endphp>
<label class="form-check-label" for="cacheStatus">
With Cash
</label>
<input class="form-check-input" type="checkbox" name="activaton" value="active" id="activationStatus" #php if(($wallet->is_active) == 1) {echo 'checked';} #endphp>
<label class="form-check-label" for="activationStatus">
Active
</label>
<button class="btn btn-success">Submit</button>
</form>
And the route for this goes here:
Route::post('wallets/update/{wallet}','Wallet\WalletController#update')->name('updateWallet');
Then at the Controller:
public function update(Request $request, Wallet $wallet)
{
try {
$data = $request->validate([
'title' => 'required',
'activation' => 'nullable',
'cachable' => 'nullable'
]);
$wallet->title = $data['title'];
if (!empty($data['activation'])) {
$wallet->is_active = 1;
} else {
$wallet->is_active = 0;
}
if (!empty($data['cachable'])) {
$wallet->is_cachable = 1;
} else {
$wallet->is_cachable = 0;
}
$wallet->save();
flash()->overlay('Updated!', 'Your data edited successfully.', 'success');
}catch (\Exception $e) {
dd($e);
}
return redirect(url('admin/wallets/index'));
}
It works fine and perfect since I'm not adding any method name in the blade.
But when I try this, I get this error:
The PUT method is not supported for this route. Supported methods: POST.
And also when I add method('PATCH') instead of method('PUT'), I get this:
The PATCH method is not supported for this route. Supported methods: POST.
So what is going wrong here?
When is the proper time for using PUT and PATCH methods and how to properly use them?
it's standard to use post request when we are storing something for the first time and put/patch request when we are updating something. you can use post request in both though.
but html form method accepts either get or post request. you can't use put/patch/delete on form method attribute. we use method spoofing to use those request with form using method('PUT') which creates a new input field.
<input type="hidden" name="_method" value="PUT">
this determines the form request type. but for this to work your form submit url needs to be declared as a put route (patch if you want to use patch request)
Route::put('wallets/update/{wallet}','Wallet\WalletController#update')->name('updateWallet');
changing method in form won't change your defined route type. you have to change it yourself. you have to determine which type of request you will use and both form and route have to use the same type of request.
When you change method in form at blade file, You must to change method in route file:
Route::put('wallets/update/{wallet}','Wallet\WalletController#update')->name('updateWallet');
And change method put in form:
<form>
{{ method_field('PUT') }}
</form>

$request->hasFile() returns false when uploading

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.

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

Input file in laravel 5.2?

I'm trying to upload a file, but it fails when the request lands to the controller.
With fails i mean that if i try $request->hasFile("filename") always returns false.
Is there some specific field that I have to specify in the view?
This is a snippet of the view:
<body>
<form action="{{url('dev/tester')}}" method="POST">
{{csrf_field()}}
<input type="file" name="file">
<button type="submit">Test</button>
</form>
</body>
And here is the controller
class Tester extends Controller
{
public function index(Request $request)
{
if($request->hasFile('file'))
{
dd('Got the file');
}
dd('No file');
}
public function testView()
{
return view('tests.file_upload');
}
}
I always get returned 'No file'.
Any clue? I've even check the php.ini to see if there was a size limitation but it's all set to 32M as MAMP's pro default settings...
Check if you may have forgotten to add enctype="multipart/form-data" in form
You must enabling upload form to your form,
there is 2 ways to do it :
By using HTML
<form action="{{url('dev/tester')}}" method="post" enctype="multipart/form-data">
By using laravel Form & HTML (https://laravelcollective.com/docs/5.2/html)
{!! Form::open( [ 'action' => url( 'dev/tester' ), 'method' => 'post', 'files' => true ] ) !!}
// Your form
{!! Form::close() !!}
This should work like a charm!
Try adding the enctype="multipart/from-data" to your form, then it should work!

Categories