Why my input validation is not working (laravel 5)? - php

I am using Laravel 5 and I want to use input validation for my form. But my validation is not working. Do you know why? Here is the view:
<div class="form-group"><br>
<label for="jenis_surat" class="control-label col-sm-2">Jenis Surat</label>
<div class="col-sm-7">
<script type="text/javascript">
#if($errors->any())
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
</script>
<input class="form-control" type="text" name="jenis_surat" id="jenis_surat">
</div>
<div class="col-md-1">
<input class="form-control" type="hidden" name="_token" value="{{ Session::token() }}">
<a class="btn btn-success" data-toggle="modal" data-target="#konfirmasi_submit_jenis_surat">Submit</a>
</div>
</div>
and this is the controller:
public function tambahjenissurat(Request $request)
{
//input validation
$this->validate($request, [
'jenis_surat' => 'required'
]);
$jenis_surat = $request['jenis_surat'];
$jenissurat = new JenisSurat();
$jenissurat->jenis_surat = $jenis_surat;
$jenissurat->save();
return redirect()->route('jenissurat');
}

Could you please try like this?
1. Import the validator using use Validator;
2. Change the code that validates the rule as given below
$rules = array(
'jenis_surat' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator);
}

Related

Laravel validation doesn't seem to work at all

I am trying to validate the form data as they do in laravel's default authentication. It worked few days ago but now it doesn't work. If user didn't make any mistakes in form and submit it, then it successfully save data in the db. If user submit an empty form without any data or did some mistake in the form it's not showing the error message. If i add controller function code in a try catch, exception is showing as 'Invalid data'
view(form)
<form class="form-horizontal" action="{{ route('save-service-page-content') }}" method="POST" enctype="multipart/form-data">
<div class="box-body">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('file') ? ' has-error' : '' }}">
<label for="image" class="col-sm-2 control-label">Service Image</label>
<input hidden id="service_image_file" name="file"/>
<div class="col-sm-10" id="demo-upload">
<div class="dropzone needsclick dz-clickable" id="serviceImageUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
#if ($errors->has('file'))
<span class="help-block"><strong>The service image is reuired</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description" placeholder="Description goes here"></textarea>
#if ($errors->has('description'))
<span class="help-block"><strong>{{ $errors->first('description') }}</strong></span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('description_sin') ? ' has-error' : '' }}">
<label for="inputEmail3" class="col-sm-2 control-label">හැදින්වීම</label>
<div class="col-sm-10">
<textarea rows="8" class="form-control" name="description_sin" placeholder="හැදින්වීම සිංහලෙන්"></textarea>
<small class="form-text text-muted">හැදින්වීම ඇතුලත් කරන්න. (හැදින්වීම සිංහල බසින් ඇතුලත් කලොත් පමණක් එය ඉංග්‍රීසි බස වෙනුවට සිංහල බසින් දිස්වනු ඇත.)</small>
#if ($errors->has('description_sin'))
<span class="help-block"><strong>මෙම හැදින්වමෙහි අක්ෂර සහ ඉලක්කම් පමණක් ඇතුලත් විය යුතුය </strong></span>
#endif
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer clearfix">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
</form>
Controller
namespace App\Http\Controllers;
use App\Service_page_content;
use App\Service;
use File;
use Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class ServiceContent extends Controller
{
protected function validator(array $data)
{
return Validator::make($data, [
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save_page_content(Request $request)
{
$this->validator($request->all())->validate();
$service_page_content = new Service_page_content;
$service_page_content->description = $request->description;
$service_page_content->description_sin = $request->description_sin;
$file = $request->file;
$image_decode = base64_decode($file);
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = "service-page-content-".time().'.'.str_replace("image/","",$mime_type);
$image_resized = Image::make($image_data);
$image_resized->resize(1170, null, function ($constraint) {
$constraint->aspectRatio();
});
$image_resized->save(public_path("uploads/service_page_content_uploads/$imageName"));
$service_page_content->main_img_url = $imageName;
$service_page_content->save();
return redirect()->back()->with('success', ['Data Saved']);
}
}
I don't know if I'm doing it correctly on return Validator::make($data,...... or $this->validator($request->all())->validate();
I have written a custom validation rule that allows alpha numeric, spaces, brackets, '.' and ',' in AppServiceProvider boot function. It also worked few days ago. Now nothing seems to work.
It worked few days ago. Ignore the file upload part it is working perfectly I'm using Dropzone.js for it. May be I'm missing something. Any help would be appreciated !
You can validate directly on the array without calling the Validator facade.
protected function validator(Request $request)
{
return $request->validate([
'file' => 'required',
'description' => 'nullable|alpha_num_spaces_brackets',
'description_sin' => 'nullable|alpha_num_spaces_brackets',
]);
}
public function save(Request $request){
$this->validator($request);
}

Laravel 5.2 Validation Error not appearing in blade

I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.
Here is the controller:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}
Here is the route:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('index');
})->name('main');
Route::post('/saveUser',[
'uses' => 'AppController#saveUser',
'as'=>'saveUser',
]);
});
Here is the blade view page:
#extends('layouts.master')
#section('title')
Create User
#endsection
#section('content')
#include('partials.message-block')
<div class="container" >
<h3> Student Register </h3>
{!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST')) !!}
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required placeholder="Name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required placeholder="email">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" name="phone" class="form-control" required placeholder="phone">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="course_id" >
#foreach($input as $row)
<option value="{{$row->id}}">{{$row->name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
#endsection
And here is the error-message block:
#if(count($errors) > 0)
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
#if(Session::has('message'))
<div class="row">
<div class="col-md-4 col-md--offset-4 success">
{{Session::get('message')}}
</div>
</div>
#endif
Try to remove web middleware if you're using 5.2.27 or higher. The thing is now Laravel automatically applies web middleware to all routes inside routes.php and if you're trying to add it manually you can get errors.
app/Providers/RouteServiceProvider.php of the 5.2.27 version now adds web middleware to all routes inside routes.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Use Below line in your controller
use Validator;
Add below code in your controller function where your request is sent.
$validator = Validator::make($request->all(), [
'fname' => 'required|max:20|min:4',
'uemail' => 'required|email',
'message' => 'required',
]);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withErrors($messages)->withInput($request->all());
}
In your view page
#if ($errors->any())
<label for="fname" class="error">{{ $errors->first('fname') }}</label>
#endif
For display individual field wise error.
if you are using laravel 5.2+ then please use the below code.
Moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php
Alexey is correct and if you're not comfortable with that then you can just add this code into your view for the session messages to show.
#if(Session::has('message'))
<div class="alert alert-success">{{Session::get('message')}}</div>
#endif
#if(count($errors)>0)
<ul>
#foreach($errors->all() as $error)
<li class="alert alert-danger">{{$error}}</li>
#endforeach
</ul>
#endif
I've done this in laravel 5.5. Please do confirm if this helps you out.

User Edit Resource not working

I have a user resource with is linked in the users table.
My Route:
Route::resource('user', 'UserController');
UserController.php
public function edit($id)
{
$user = User::find($id);
return view('user.edit')->with(array('user'=>$user));
}
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
}
And my View
{!! Form::model($user, array('route' => array('user.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) !!}
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
#endif
#endforeach
</div>
<div class="form-group"><label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10"><input type="text" name="name" id="name" value="{{$user->name}}" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">ID Number</label>
<div class="col-sm-10"><input type="text" name="id_number" id="id_number" value="{{$user->id_number}}" class="form-control"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Save changes</button>
</div>
</div>
{!! Form::close() !!}
So with this setup I expect that when click the submit button on my page it will go in the update() function just like my other resource. But problem is when I click submit it will direct me to
http://localhost/hrs/public/user/1
and a white blank page with no errors what so ever. So it means it's going to my update function? I am following same pattern with my other resource and this is the only one not working.
You have wrong web server configuration. You should point your web server (usually Apache or nginx) to a public directory of your Laravel project. After that restart web server.
For example for Apache correct configuration will be something like this:
DocumentRoot "C:/xampp/htdocs/hrs/public"
<Directory "C:/xampp/htdocs/hrs/public">
Found the problem, I don't have the else part of the validation. as that is where the event goes to. Since I don't have it, it will do nothing.
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
else
{
dd($rules);
}

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.

Laravel form data not saving in neo4j graph DB

I wrote a laravel form, its screen shot is as given below:
And I use neo4j for storing that form data.
Here is the code:
app/views/duck-form.blade.php
<!doctype html>
<html>
<head>
<title>Laravel Form Validation!</title>
<!-- load bootstrap -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
body { padding-bottom:40px; padding-top:40px; }
</style>
</head>
<body class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="page-header">
<h1><span class="glyphicon glyphicon-flash"></span> Register! </h1>
</div>
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
<!-- FORM STARTS HERE -->
<form method="POST" action="/ducks" novalidate>
<div class="form-group #if ($errors->has('name')) has-error #endif">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your name" value="{{ Input::old('name') }}">
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('email')) has-error #endif">
<label for="email">Email</label>
<input type="text" id="email" class="form-control" name="email" placeholder="Enter your email id" value="{{ Input::old('email') }}">
#if ($errors->has('email')) <p class="help-block">{{ $errors->first('email') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('password')) has-error #endif">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name="password">
#if ($errors->has('password')) <p class="help-block">{{ $errors->first('password') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('password_confirm')) has-error #endif">
<label for="password_confirm">Confirm Password</label>
<input type="password" id="password_confirm" class="form-control" name="password_confirm">
#if ($errors->has('password_confirm')) <p class="help-block">{{ $errors->first('password_confirm') }}</p> #endif
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
</body>
</html>
1. I added 'Artdarek\Neo4j\Neo4jServiceProvider' to providers array in app/config/app.php.
2. I added neo4j configuration in app/config/database.php
'neo4j' => [
'default' => [
'host' => 'localhost',
'port' => 7474,
'username' => null,
'password' => null,
],
],
3. Then I added a controller for that form:
<?php
class DuckController extends BaseController {
public function showWelcome()
{
return View::make('duck');
}
}
4. This is my routes.php.
<?php
Route::get('/', function()
{
return View::make('hello');
});
// route to show the duck form
Route::get('ducks', function()
{
return View::make('duck-form');
});
// route to process the ducks form
Route::post('ducks', array('before' => 'csrf', function()
{
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:ducks', // required and must be unique in the ducks table
'password' => 'required',
'password_confirm' => 'required|same:password' // required and has to match the password field
);
// create custom validation messages ------------------
$messages = array(
'required' => 'The :attribute is really really really important.',
'same' => 'The :others must match.'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules, $messages);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back with error messages
$messages = $validator->messages();
// also redirect them back with old inputs so they dont have to fill out the form again
// but we wont redirect them with the password they entered
return Redirect::to('ducks')
->withErrors($validator)
->withInput(Input::except('password', 'password_confirm'));
} else {
// validation successful ---------------------------
// our duck has passed all tests!
// let him enter the database
// create the data for our duck
$duck = new Duck;
$duck->name = Input::get('name');
$duck->email = Input::get('email');
$duck->password = Hash::make(Input::get('password'));
// save our duck
$duck->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
return Redirect::to('ducks')
->with('messages', 'Hooray!');
}
}));
5. This is my model file for form:
<?php
class Duck extends Eloquent {
protected $fillable = array('name', 'email', 'password');
}
6. This is my model for neo4j:
<?php
//use Illuminate\Auth\EloquentUserProvider;
class database extends Eloquent {
public function index($name, $email, $password, $password_confirm) {
$formData = Neo4j::makeNode();
$formData->setProperty('name',$name)
->setProperty('email',$email)
->setProperty('password',$password)
->setProprty('password_confirm',$password_confirm)
->save();
}
}
When I click on that submit button in that form, I get this error:
[ Edit ]
I was working on it:
This is the new error which I got:
Is it a csrf token issue?
It is pointing to:
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
I'm unable to resolve it since 5 hours and data isn't getting stored in neo4j DB. How can I fix it?
When using the CSRF Protection Filter, your form must be declared in your blade as such:
{{ Form::open(array('method' => 'POST', 'action' => URL::to("/ducks"))) }}
And closed:
{{ Form::close() }}
This will render the same form in your html as using:
<form method="POST" action="{{ URL::to("/ducks") }}">...</form>
But will also add the hidden _token element that you are missing:
<input type="hidden" name="_token" value="value_of_token"/>
Hope that helps!
Edit
Or, if you don't want to recreate your <form>, you may simply use:
{{ Form::token() }}
Somewhere inside your existing <form> tag to create it.
Your code looks fine, might be you need to run
composer dump-autoload

Categories