Laravel validation throwing route error - validation

I am attempting a basic validation check on form fields in the controller. The code is below:
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
The parameter passed to Redirect::to here is the folder members and registration view which resides in it. The problem is being caused by this line specifically:
return Redirect::to('members.registration')->withErrors($validator);
When it is commented out, form submission returns a blank white page. Otherwise the following error in the picture is shown
The route file has the following content:
Route::get('/', 'MainController#index');
Route::get('membersaccess', array('as' => 'membersaccess', 'uses' => 'MainController#loadMembersAccess'));
Route::get('signin', array('as' => 'signin', 'uses' => 'MembersController#loadlogin'));
Route::get('signup', array('as' => 'signup', 'uses' => 'MembersController#loadRegistration'));
Route::post('postLogin', array('as' => 'postLogin', 'uses' => 'MembersController#login'));
Route::post('postRegistration', array('as' => 'postRegistration', 'uses' => 'MembersController#registration'));
function containing the validation part is:
public function registration()
{
$email = Input::get('email');
$password = md5(Input::get('password'));
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
//echo $email;
$validator = Validator::make(
array('email' => 'required|min:7'),
array('password' => 'required|min:7'),
array('firstName' => 'required'),
array('lastName' => 'required'));
if ($validator->fails())
{
// The given data did not pass validation
/*Get error msgs from validator*/
return Redirect::to('members.registration')->withErrors($validator);
}
}
and the form for reference:
#if(Session::has('errors'))
<? $errors = Session::get('errors'); ?>
<h3> {{ $errors->first('email') }}</h3>
#endif
{{ Form::open(array('route' => 'postRegistration')) }}
{{ Form::text('email', null, array('placeholder'=>'Email', 'class' => 'randomfieldsize' ) ) }}
{{ Form::password('password', array('placeholder'=>'Password', 'class'=>'randomfieldsize' ) ) }}
{{ Form::text('firstname', null, array('placeholder'=>'First Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::text('lastName', null, array('placeholder'=>'Last Name', 'class' => 'randomfieldsize' ) ) }}
{{ Form::select('country', array('' => '', 'saudi' => 'Saudi Arabia', 'uae' => 'UAE')) }} <br><br>
{{Form::submit('Proceed', ['class' => 'button [radius round]'])}}
{{ Form::close() }}

Try this:
return Redirect::route('signup')->withErrors($validator);
You have no route defined as members.registration, so that may be the problem.
To show errors I usually use this (styling with bootstrap):
#if( $errors->has() )
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<ul>
#foreach ( $errors->all('<li>:message</li>') as $error )
{{ $error }}
#endforeach
</ul>
</div>
#endif
Edit: Ugh, didn't noticed it before, but your validation code is wrong. Please refer to http://laravel.com/docs/validation It should be something like this:
$email = Input::get('email');
$password = Input::get('password'); // Better to hash the password in another place, since md5 can create a hash even of an empty string. Also, please use laravel hash utility instead of md5: http://laravel.com/docs/security#storing-passwords
$firstName = Input::get('firstName');
$lastName = Input::get('lastName');
$country = Input::get('country');
$validator = Validator::make(
compact('email', 'password', 'firstName', 'lastName', 'country'),
array(
'email' => 'required|min:7',
'password' => 'required|min:7'
'firstName' => 'required'
'lastName' => 'required'
));

Related

Laravel & Ajax send HTML form with errors

Here is an action:
public function postMessageAjax(Request $request)
{
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
return view('Guestbook.postMessage');
}
And here is the view:
{!! BootForm::open(['id' => 'messageForm']) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img('flat') !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
The problem is that Laravel somehow determines that that is an Ajax request and set an JSON of errors (if they're present) to Response instead of retrieving HTML code of form plus errors messages for each input individually. The question is: how do I force it to render the view with errors like if it weren't through Ajax?
UPDATE: this is what I want to get (the form itself and errors if they're present):
For #OuailB:
I've just noticed that when I do a normal POST request, it redirects me to the same page through a GET request so it seems like the error messages actually appear in the GET's body, not POST's so maybe there is no way. I'll think about it, thanks for your help!
You can create validator manually, and if it fails return what you want:
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput($request->all());
}
Try this code:
public function postMessageAjax(Request $request)
{
$validator = Validator::make($request->all(), [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
if ($validator->fails()) {
return view('Guestbook.postMessage')
->withErrors($validator);
}
// Store your message here
}
Edit :
For displaying the errors, you can add this code into your view :
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel 5.3 - Blade not working

When I try to load my project on web browser. It shows header and footer, but the middle section containing form is missing, and I don't understand what am I doing wrong?
views/welcome.blade:
<!DOCTYPE html>
<html lang="en">
<head>
#include('partials._head')
</head>
<body>
#include('partials._nav')
<div class="container">
#include('partials._messages')
#yield('content')
#include('partials._footer')
</div>
#include('partials._javascript')
</body>
</html>
views/user_auth/user_register.blade:
#extends('welcome')
#section('title')
Welcome!!
#endsection
#section('content')
{!! Form::open(['route' => 'signup']) !!}
{{ Form::label('user_name','Name:') }}
{{ Form::text('user_name',null,['class' => 'form-control']) }}
{{ Form::label('email','E-mail:') }}
{{ Form::text('email',null,['class' => 'form-control']) }}
{{ Form::label('mobile_num','Mobile No.:') }}
{{ Form::text('mobile_num',null,['class' => 'form-control']) }}
{{ Form::label('address','Address:') }}
{{ Form::text('address',null,['class' => 'form-control']) }}
{{ Form::label('state','State:') }}
{{ Form::text('state',null,['class' => 'form-control']) }}
{{ Form::label('city','City:') }}
{{ Form::text('city',null,['class' => 'form-control']) }}
{{ Form::label('district','District:') }}
{{ Form::text('district',null,['class' => 'form-control']) }}
{{ Form::submit('Register',array('class' => 'btn btn-success btn-lg btn- block form-spacing-top')) }}
{!! Form::close() !!}
#endsection
RegisterController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
public function getRegistrationPage()
{
return view('user_auth.user_register');
}
public function postSignUp(Request $request)
{
$this -> validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:20',
'mobile_num' => 'required|digits:10',
'address' => 'required',
'city' => 'required',
'district' => 'required',
'state' => 'required',
'password' => 'required|min:4'
]);
$email = $request['email'];
$name = $request['name'];
$mobile_num = $request['mobile_num'];
$address = $request['address'];
$city = $request['city'];
$district = $request['district'];
$state = $request['state'];
$password = bcrypt($request['password']);
$user = new User();
$user->email =$email;
$user->name = $name;
$user->mobile_num = $mobile_num;
$user->address = $address;
$user->city = $city;
$user->district = $district;
$user->state = $state;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
Auth::login($user);
}
public function postSignIn(Request $request)
{
$this -> validate($request,[
'mobile_num' => 'required',
'password' => 'required'
]);
if(Auth::attempt(['mobile_num' => $request['mobile_num'], 'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
public function getDashboard()
{
return view('pages.dashboard');
}
}
routes/web.php :
Route::group(['middleware' => ['web']], function(){
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup',[
'uses' => 'RegisterController#postSignUp',
'as' => 'signup'
]);
Route::post('/signin',[
'uses' => 'RegisterController#postSignIn',
'as' => 'signin'
]);
Route::get('/dashboard',[
'uses' => 'RegisterController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Route::get('/register',[
'uses' => 'RegisterController#getRegistrationPage',
'as' => 'register',
'middleware' => 'auth'
]);
});
You need to return user_register view which should extend layout (in this case it called welcome):
#extends('welcome')
Or you can call welcome and include user_register view:
#include('user_auth.user_register')
It depends on what you want to achieve, but renaming welcome to layout and extending it looks like right solution here.
Also rename files to .blade.php, because now names are like welcome.blade instead of welcome.blade.php.
Your code is correct but Please check your route file Have you called user_register route?
You have set a welcome page as a layout file so When you will call welcome page it displays only header & footer file which you have included.

Laravel Multiple Inputs Search 4.2

I am making a multiple inputs search query and i need help cause i do not know how to exactly to do this i have read all the documentation and i did not understand it.Now i am stuck in the controller.....
Also i would really appreciate of how to call the informations that i want in in the show.blade ! Thank you for any help !
Index blade
<div class="panel-body">
<div class="form-group">
<div><h4></h4></div>
<div class="form-group col-md-4">
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('name', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'name...')) }}
{{ Form::text('lastname', null, array('class' => 'form-group form-control', 'placeholder' => 'lastname...')) }}
{{-- {{ Form::text('id', null, array('class' => 'form-group form-control', 'placeholder' => 'id...')) }}
{{ Form::text('user-seminars', null, array('class' => 'form-group form-control', 'placeholder' => 'Class tha is enrolled...')) }}
{{ Form::text('user-class', null, array('class' => 'form-group form-control', 'placeholder' => 'Class that belongs...')) }}
{{ Form::text('user-annex', null, array('class' => 'form-group form-control', 'placeholder' => 'Department that belongs...')) }}
{{ Form::text('type', null, array('class' => 'form-group form-control', 'placeholder' => 'User type...')) }}
{{ Form::text('date_created', null, array('class' => 'form-group form-control', 'placeholder' => 'date created account...')) }}
{{ Form::text('date_enrolled', null, array('class' => 'form-group form-control', 'placeholder' => 'date enrolled in class...')) }}
routes
Route::get('users/index', 'UserController#index');
Route::get('users/search', 'UserController#search');
Route::get('users/show', 'UserController#show');
UserContoller
public function index(){
return View::make('user.index');
}
public function search(){
return View::make('user.show');
}
public function show(){
return View::make('user.show');
}
USERS TABLE
id , firstname,last_name,etc etc etc
public function search(Request $request){
$users = App\User::where('firstname',$request->name)
->orWhere('lastname',$request->lastname)
->orWhere('id',$request->id)
// more orWhere Clause
->get();
return View::make('user.show',compact('users'));
}
public function show($id){
$user = App\User::find($id);
return View::make('user.show',compact('user'));
}
Why are you using return View::make('user.show') to render two different resources?
the first thing i see its the form action
your code
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
should be
{{ Form::open(array('action' => array('users/search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
the controller is the fun part. if you're looking for all the inputs to be required you should validate it first
//first we set the inputs rultes
$data = Input::all();
$rules = array(
'name' => 'required',
'lastname' => 'required',
//rest of the inputs that are required
);
//then we use the validator method
$val = Validator::make($data,$rules);
if($val->fails())
{
/*redirect to the form again, you can set errors with session
or ->withError($validator)*/
return Redirect::back();
}
then you make your query
$user = User::where('name','=',$data['name'])
->where('lastname','=',$data['lastname'])
//more where('field','=','value')
->get();
if the fields arent required you only make the query with
$user = User::where('name','=',$data['name'])
->orWhere('lastname','=',$data['lastname'])
//more orWhere('field','=','value')
->get();
and finally you return your result to the view like:
return View::make('user.show')->with('user',$user);

laravel Undefined offset: 0

I am trying to diplay an error mesasge in case the field selected is duplicated in db.For this I am using laravel validation required unique. I am having problem with redirect
Here is store controller
public function store() {
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id'),
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
// Validation has failed.
return Redirect::to('insur_docs/create')->with_input()->with_errors($validation);
} else {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
// redirect
return Redirect::to('/');
}
}
Here is the route
Route::get('insur_docs/create', array('as' => 'insur_docs.create','uses' => 'Insur_DocController#create'));
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_create.blade.php
<div id="div-1" class="body">
{{ Form::open(array('url' => 'insur_docs/store', 'class'=>'form-horizontal','id'=>'inline-validate')) }}
<div class="form-group">
{{ Form::label('ownership_cert', 'Ownership Certificate', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('ownership_cert', array('' => '', '1' => 'Yes', '0' => 'No'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid ownership certificate',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('authoriz', 'Authorization', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('authoriz', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid authorization date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('drive_permis', 'Drive Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('drive_permis', array('' => '', '1' => 'Active', '0' => 'Not active'), '', array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid drive permission',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('sgs', 'SGS', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('sgs', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid sgs date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('tpl', 'TPL', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('tpl', isset($v->sgs) ? $v->sgs : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid tpl date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('kasko', 'Kasko', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('kasko', isset($v->kasko) ? $v->kasko : '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid kasko date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('inter_permis', 'International Permission', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Helpers\Helper::date('inter_permis', '' , array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid international permission date',
'class' => 'form-control'))
}}
</div>
</div>
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
{{ $errors->first('car') }}
</div>
</div>
{{ Form::submit('Save', array('class' => 'btn btn-success btn-line')) }}
<input type="button" value="Back" class="btn btn-danger btn-line" onClick="history.go(-1);
return true;">
<div>
#foreach($errors as $error)
<li>{{$error}}</li>
#endforeach
</div>
{{ Form::close() }}
I t displays this error :
Undefined offset: 0
It might be that you are using a get, using post might help. Other than that you are mixing model and controller code. It's always a good idea to seperate these. For instance your redirects should be done inside the controller and not in the model.
http://laravel.com/docs/validation
http://laravelbook.com/laravel-input-validation/
http://culttt.com/2013/07/29/creating-laravel-4-validation-services/
It's also better to do stuff on $validator->passes() and then else return with errors.
Controller
public function store() {
$data = [
"errors" => null
];
$rules = array(
'car' => array('required', 'unique:insur_docs,car_id')
);
$validation = Validator::make(Input::all(), $rules);
if($validation->passes()) {
$data = new InsurDoc();
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->car_id = Input::get('car');
$data->save();
return Redirect::to('/');
} else {
$data['errors'] = $validation->errors();
return View::make('pages.insur_docs_create', $data);
}
}
Your errors will be available in your view under $errors. Just do a {{var_dump($errors)}} in your blade template to verify that they are there.
View
#if($errors->count() > 0)
<p>The following errors have occurred:</p>
<ul>
#foreach($errors->all() as $message)
<li>{{$message}}</li>
#endforeach
</ul>
#endif
I Think this is a really better answer from this refrenece
Laravel 4, ->withInput(); = Undefined offset: 0
withInput() doesn't work the way you think it does. It's only a function of Redirect, not View.
Calling withInput($data) on View has a completely different effect; it passes the following key value pair to your view: 'input' => $data (you get an error because you're not passing any data to the function)
To get the effect that you want, call Input::flash() before making your view, instead of calling withInput(). This should allow you to use the Input::old() function in your view to access the data.
Alternatively, you could simply pass Input::all() to your view, and use the input[] array in your view:
View::make(...)->withInput(Input::all());
which is translated to
View::make(...)->with('input', Input::all());
As for your comment, I recommend doing it like so:
$position_options = DB::table('jposition')->lists('friendly','id');
$category_options = DB::table('jcategory')->lists('friendly','id');
$location_options = DB::table('jlocation')->lists('friendly','id');
$category = Input::get('category');
$location = Input::get('location');
$type = Input:: get('type');
$data = compact('position_options', 'category_options', 'location_options', 'category', 'type', 'location');
return View::make('jobsearch.search', $data);
also thinks about laravel resource controller. because when we call no parameter get method, it redirects to the show method with ignoring our function name.
eg:-Route::get('hasith', 'Order\OrderController#hasith');----->
this parameter rederect to this function
public function show($id, Request $request) {
//code
}

Laravel 4: Route::post return URL with model name in brackets instead of id

I am building a post/comment system, with the comment form inside the post view. So, when I'm watching a post in the url http://example.dev/post/1 and click on the form submit buttom the url goes to http://example.dev/post/%7Bpost%7D where %7B = { and %7D = }).
I think the controller associated to the url post method doesn't even start.
My routes:
Route::model('post','Post');
Route::get('partido/{post}', 'FrontendController#viewPost');
Route::post('partido/{post}', array(
'before' => 'basicAuth',
'uses' => 'FrontendController#handleComment'
)
);
My viewPost controller:
public function viewPost(Post $post)
{
$comments = $post->comments()->get();
return View::make('post')
->with(compact('comments'))
->with(compact('posts'));
}
My handleComment controller:
public function handleComment(Post $post)
{
// Get the data
$data = Input::all();
// Build the rules
$rules = array(
'title' => 'required',
'description' => 'required',
);
// Error messages
$messages = array(
'title.required' => 'Title required.',
'description.required' => 'Description required.',
);
// Validator: He Comes, He sees, He decides
$validator = Validator::make($data, $rules, $messages);
if ($validator->passes()) {
// Save the new comment.
$comment = new Comment;
$comment->title = Input::get('title');
$comment->description = Input::get('description');
$post->comments()->save($comment);
return Redirect::to('post/'.$post->id.'');
}
else {
return Redirect::to('post/'.$post->id.'')->withErrors($validator);
}
}
And the form in the view:
{{ Form::open(array(
'action' => 'FrontendController#handleComment', $post->id
)) }}
<ul class="errors">
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
{{ Form::label('title', 'Title')}}<br />
{{ Form::text('title', '', array('id' => 'title')) }}
<br />
{{ Form::label('description', 'Description')}}<br />
{{ Form::textarea('description', '', array('id' => 'description')) }}
<br />
{{ Form::submit('Submit') }}
{{ Form::close() }}
You need another array for the Form::open() - try this:
{{ Form::open(array('action' => array('FrontendController#handleComment', $post->id))) }}

Resources