Laravel form mime type validation - php

Form is file uploader. Laravel doesnt give me error if validation fails on mime type. If it fails on input required it gives me error on my upload page properly. It looks like validation is right but it only doesnt give me back error if mime type is wrong, because it doesnt upload file if file is wrong.
route
Route::post('/newfile', function (Request $request) {
$validator = Validator::make($request->all(), [
'userFile' => 'required|mimes:zip',
]);
if ($validator->fails()) {
return redirect('/upload')
->withErrors($validator);
} else {
view
#include('errors.errors')
<form action="{{ url('newfile') }}" method="POST" id="uploadForm" class="form-horizontal" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input name="userFile" id="userFile" type="file" />
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<div>
<button type="submit" id="btnSubmit" value="Submit" class="btn btn-success">Upload</button>
<div class="progress">
</div>
</div>
</form>
error
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Fixed, my javascript code for upload blocked errors from validator.

Related

From validation Throws error The GET method is not supported for this route. Supported methods: POST."

i am new to laravel..Kind of stuck at this place. Tried many solutions for this but none worked yet, There are similar question but most unresolved, or proper evident solution not posted yet(from google,stackoverflow ..etc)
i have defned a custom route
Route::post('/ComplaintGenerate', 'ComplaintsController#generate');
whenever i submit the view with 'POST' method as
<form action="/ComplaintGenerate" method="POST" >
without any validation rule in my Complaintscontroller everything works fine and i can save data. but when i put validation either through Requests or direct it throws error Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
if i remove validation everything works fine. I also tried with GET method but still dint work.
A little peace of advice will be very much appreciated.
Web.route
Route::middleware(['auth'])->group(function(){
Route::post('/Complaint', 'ComplaintsController#find');
Route::post('/ComplaintGenerate', 'ComplaintsController#generate');
Route::post('/Complaint/{Complaint}', 'ComplaintsController#save_customer');
Route::resource('Complaints', 'ComplaintsController');
Route::resource('Occupancies', 'OccupanciesController');
Route::resource('Customers', 'CustomersController');
Route::resource('Services', 'ServiceController');
Route::resource('ServiceTeams', 'ServiceTeamController');
Route::get('/home', 'HomeController#index')->name('home');});
My controller:
public function generate(GenerateInitialComplaintRequest $request)
{
$complaint = Complaint::find($request->complaint_id);
$complaint->update([
'complaint_date'=>$request->complaint_date,
'complaint_description'=>$request->complaint_description,
]);
return redirect(route('Complaints.index')->with('complaint', Complaint::all()));
}
my View:
<div class="container my-5">
<div class="col d-flex justify-content-center my-4">
<div class="card">
<div class="card-header">
<form action="/ComplaintGenerate" method="POST" >
#csrf
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-row">
<div class="form-group col-md-6">
<label for="complaint_id">Complaint Number</label>
<input type="text" class="form-control" id="complaint_id" name="complaint_id" value="{{$complaint->id}}" readonly >
</div>
<div class="form-group col-md-6">
<label for="complaint_date">Complaint Date</label>
<input type="text" class="form-control" id="complaint_date" name="complaint_date">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="complaint_description">Complaint Description</label>
<textarea class="form-control" id="complaint_description" name="complaint_description" rows="5"></textarea>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
What is the route for displaying your form? When validation fails, Laravel makes redirection using GET method to the route it was displayed from.
I assume the form might be displayed in the find method of your ComplaintsController, and when validation fails, there's redirection to this route and that is what throws an error.
Can you also show your validation methods and what data are you trying to send through form?
i found the solution as mentioned by Ankur Mishra and Aryal,
We have to remember as mentioned by Aryal When validation fails, Laravel makes redirection using GET method to the route it was displayed from. And i displayed my form through below
Route::post('/Complaint/{Complaint}', 'ComplaintsController#save_customer');
Controller method:
public function save_customer($id)
{
$complaint = Complaint::create([
'customer_id'=>$id
]);
// $complaint = Complaint::whereCustomer_id($id)->firstorfail();
return view('complaints.initial_complaint')->with('complaint', $complaint);
}
'complaints.initial_complaint' is the view which has the form which gave me the error of
The GET method is not supported for this route. Supported methods: POST. on submission
So i change POST route to GET :-
Route::middleware(['auth'])->group(function(){
//Route::resource('Complaints', 'ComplaintsController');
Route::get('/Complaint', 'ComplaintsController#find');
Route::get('/Complaint/{Complaint}', 'ComplaintsController#save_customer');
Route::get('/ComplaintGenerate', 'ComplaintsController#generate');
Route::resource('Complaints', 'ComplaintsController');
Route::resource('Occupancies', 'OccupanciesController');
Route::resource('Customers', 'CustomersController');
Route::resource('Services', 'ServiceController');
Route::resource('ServiceTeams', 'ServiceTeamController');
Route::get('/home', 'HomeController#index')->name('home');
});
and in view i passed GET as hidden method
<form action="/ComplaintGenerate" method="POST" >
#csrf
#method('GET')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="form-row">
<div class="form-group col-md-6">
<label for="complaint_id">Complaint Number</label>
<input type="text" class="form-control" id="complaint_id" name="complaint_id" value="{{$complaint->id}}" readonly >
</div>
<div class="form-group col-md-6">
<label for="complaint_date">Complaint Date</label>
<input type="text" class="form-control" id="complaint_date" name="complaint_date">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<label for="complaint_description">Complaint Description</label>
<textarea class="form-control" id="complaint_description" name="complaint_description" rows="5"></textarea>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
and now it is working me.. Just posted so if anybody could use it for future reference
you should add
Route::get('/ComplaintGenerate', 'ComplaintsController#generate');
Route::post('/ComplaintGenerate', 'ComplaintsController#generate');

Input type "file" returns EMPTY in Laravel php

I have this problem getting my string to an input type file, I'd try changing the input type to text, and when I return $request it works (just with type text, with file type it returns empty).
I'd put enctype="multipart/form-data" but that still empty value for file input.
web.php
Route::get('/profile', 'miPerfilController#index')->name('profile');
Route::post('/profile/update', 'miPerfilController#updatePhoto')->name('profile.update');
updatePhoto.blade.php
<form class="form-group" method="POST" action="/profile/update" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="modal fade row" id="updatePhoto">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="card-body">
<div class="mb-5 form-group" >
<h3 class="pull-left">Update profile image</h3>
<button type="button" class="close pull-right" data-dismiss="modal">
<span>
×
</span>
</button>
</div>
<label v-for="error in errors" class="text-danger">#{{ error }}</label>
<div class="form-group">
<label for="name">Choose image<span class="help"></span></label>
<br><br>
<input type="file" name="profile_image" id="profile_image"
class="form-control">
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Guardar">
</div>
</div>
</div>
</div>
</div>
</form>
miPerfilController.php
public function updatePhoto( Request $request )
{
return $request;
}
Result
write the form tag like this
<form class="form-group" method="POST" action="{{ route('profile.update') }}" enctype="multipart/form-data">
Try this
public function updatePhoto( Request $request , $id )
{
return $request->all();
}
You should try to get files using $request->file() method.
public function updatePhoto( Request $request , $id ){
if ($request->file('profile_image')) {
print_r($request->file('profile_image'));
} else {
echo 'file not found';
}
}
Thanks.

how to pass value from input form into another page in laravel

Excuse me, i'm new in learning about Laravel and I have a problem about show data value from form input.
I have create.blade.php :
#extends('layouts.master')
#section('content')
<div class="container">
<div class="header">
<h1><b>Create an account</b></h1>
<h5>Welcome to Konoha Village</h5>
</div>
{{ csrf_field() }}
#if(isset($name))
<div class="alert alert-warning alert-dismissible" role="alert">
Halo <strong>{{$name}}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">$times;</span>
</button>
</div>
#endif
<div class="form">
<form action="{{ url('final-test') }}" method="post" id="form1">
<div class="form-group">
<input name="name" id="name" class="form-control" placeholder="Your Full Name"/>
</div>
<br>
<div class="form-group">
<input style="cursor:pointer" type="submit" class="btn btn-primary" id="submit" value="Show into Dashboard">
</div>
<div class="form-group">
</div>
</form>
</div>
</div>
#endsection
and my controller with name AccController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AccController extends Controller
{
public function create() {
return view('home.create');
}
public function show(Request $r) {
$soul = $r ->name;
$pesan = "Your name is {$r->name}";
}
}
and my route in web.php :
//route to get play form
Route::get ('start', 'AccController#create' )->name('home.create');
Route::post('final-test', 'AccController#show');
i want to show in another page view that i called show.blade.php :
#extends('layouts.master')
#section('content')
<div>
{{$name = Input::get('name')}}
<h1>Your name is {{ $pesan }}</h1> </div>
#endsection
nothing's error in the end but it couldn't show the value from the input form, would you help me please?
Regards, Aga.
Your web.php:
//route to get play form
Route::get('/start', 'AccController#create')->name('home.create');
Route::post('/final-test', 'AccController#show')->name('home.show');
Added a name home.show to the route final-test.
Your AccController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AccController extends Controller
{
public function create()
{
return view('home.create');
}
public function show(Request $r)
{
$soul = $r->name;
return view('home.show')->with('soul', $soul);
}
}
Your show.blade.php:
#extends('layouts.master')
#section('content')
<div>
<h1>Your name is {{ $soul }}</h1>
</div>
#endsection
Your create.blade.php:
#extends('layouts.master')
#section('content')
<div class="container">
<div class="header">
<h1><b>Create an account</b></h1>
<h5>Welcome to Konoha Village</h5>
</div>
#if(isset($name))
<div class="alert alert-warning alert-dismissible" role="alert">
Halo <strong>{{$name}}</strong>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">$times;</span>
</button>
</div>
#endif
<div class="form">
<form action="{{ route('home.show') }}" method="post" id="form1">
{{ csrf_field() }}
<div class="form-group">
<input name="name" id="name" class="form-control" placeholder="Your Full Name"/>
</div>
<br>
<div class="form-group">
<input style="cursor:pointer" type="submit" class="btn btn-primary" id="submit" value="Show into Dashboard">
</div>
<div class="form-group">
</div>
</form>
</div>
</div>
#endsection
Here's where the most important change has been made: I moved {{ csrf_field() }} inside the form, so you don't get The page has expired due to inactivity. Please refresh and try again. Also changed the form action to the named route {{ route('home.show') }}.
I kept your <span aria-hidden="true">$times;</span> but this will only show $times;, might need to tweak that.
You are not following conventions here. show method is to data from database. In order to show form data you have do it in store method
HTML Code
There should be some minor changes in html form
{{--Changing in just action--}}
{{-- If it doesn't accept that action then replace it with {{AccController.php#store}} --}}
<form action="AccController.php#store" method="post" id="form1">
<div class="form-group">
<input name="name" id="name" class="form-control" placeholder="Your Full Name"/>
</div>
<br>
<div class="form-group">
<input style="cursor:pointer" type="submit" class="btn btn-primary" id="submit" value="Show into Dashboard">
</div>
<div class="form-group">
</div>
</form>
Then in Controller you will get that form data in store function
public function store(Request $r) {
$soul = $r ->name;
$pesan = "Your name is {$r->name}";
return $pesan;
}
How to get it in route?
Well you are doing some mistakes in route.php. You just have to follow conventions which laravel provides us.
Replace your route code with this.
Route::resource('/posts', 'AccController.php');
Here it will automatically call all by default functions of Controller and assign them particular routes. For example Below the picture
You just have to type php artisan route:list in terminal or command prompt and you will see list of routes which you have created and which laravel creates for you along with method, URI and name. You just have to follow conventions and it will give you results automatically
Give it a try and tell me

How to prompt message if field is empty, Laravel

So I have this field for search and image field , in search form I have a button submit it works but when I clicked it and there's no input in the input field it shows error and in the image field if I don't add an image it shows error... Do I solve this through a prompt message? to let the users know that that field is empty. Here's my code for search
building.blade.php
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md"><span class="glyphicon glyphicon-search"></span> Search
</button>
</span>
</div>
{!! Form::close()!!}
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','LIKE','%'.$search.'%')->get();
return view('search',compact('offices','search'));
}
createbuilding.blade.php
{!! Form::label('Building Photo') !!}
{!! Form::file('buildingpics',array('onchange'=>'previewFile()')) !!}
<img src="../assets/imageholder.png" id="previewImg" style="height:300px; width:300px;" alt="">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default btn-md">
<span class="glyphicon glyphicon-plus"></span> Add Building
</button>
<!-- {!! Form::submit('Create Building',
array('class'=>'btn btn-primary')) !!} -->
<span class="glyphicon glyphicon-arrow-left"></span> Back
</div>
</div>
{!! Form::close() !!}
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#previewImg');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
#endsection
#section('scripts')
#endsection
You can validate it by using laravel validate method in your controller just put the validate code in your controller like
$this->validate($request, [
'field_name1' => 'required',
'field_name2' => 'required',
]);
and in your view just popup the error message so if the user is not fill the field or the field is empty then it show the error message on the submit of the request so user can easily understand what is required.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!--error ends-->
Hope this code will help you to shortout the what you want.
You can either go with HTML5 required attribute like so
<input type="text" name="search" class="form-control" placeholder="Search..." required>
or
You can user Laravel's Form Request Validation
https://laravel.com/docs/5.5/validation#form-request-validation

Laravel 5.2 form validation redirection issue

I am having some issues with the redirect when the form validation fails.
The code that I am using is the following:
// -> use Illuminate\Support\Facades\Validator;
public function subscribe(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|unique:subscriber|email',
]);
if ($validator->fails()) {
return redirect('main')
->withErrors($validator)
->withInput();
}
$email = $request->input('email');
$randomId = $this->generateRandomUserId();
$subscriberSource = $request->input('utm_source');
// ... Save user
}
And this is my form:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}">
{!! csrf_field() !!}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email"
value="{{ $email or old('email') }}">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
<i class="fa fa-btn fa-refresh"></i>Subscribe now
</button>
</div>
</div>
</form>
The users should put their email in the email field and then get validated by the above piece of code. The issue is that the user is never redirected back to the main page
You can use:
$this->validate($request, [
'email' => 'required|unique:subscriber|email',
]);
Instead of creating a new validator istance, so Laravel will automatically redirect back with all errors and all inputs to the previous page if validation fails.

Categories