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.
Related
I have a fresh installation of Laravel 5.4 using vagrant for windows.
Now as I followed through the tuts in laracast and tried the form validation it was all fine but the $errors variable just doesn't contain any error messages at all.
snippet is from PostsController
public function store()
{
$this->validate(request(), [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
Post::firstOrCreate(request(['title', 'body']));
return redirect()->route('create-post');
}
snippet from my create.blade.php
#extends('layout')
#section('content')
<main role="main" class="container">
<div class="row">
<div class="col-md-8 blog-main">
<h3 class="pb-3 mb-4 font-italic border-bottom">
Create Post Form
</h3>
<form action="/api/posts" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" placeholder="Title" name="title" value="">
<small class="text-danger">{{ $errors->first('title') }}</small>
</div>
<div class="form-group">
<label for="body">Content</label>
<textarea class="form-control" id="body" rows="5" name="body" placeholder="Contents Here.." value=""></textarea>
<small class="text-danger">{{ $errors->first('body') }}</small>
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Submit</button>
</div>
<div class="form-group">
<div class="alert alert-{{ $errors->any() ? 'danger' : 'default' }}">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
</form>
</div>
#include('partials.sidebar')
</div>
</main>
#endsection
and the result after validation failed
Is there something that I am missing or somethings wrong?
Edit
here's the snippet of my route:
Route::get('/', 'PostsController#index');
Route::get('/posts/{post}', 'PostsController#show');
Route::get('/create', function() {
return view('posts.create');
})->name('create-post');
Route::post('/posts', 'PostsController#store');
Found the answer.
Since that it's 5.4 I didnt notice that all the web.php was under a middleware called web
that that includes with it the \Illuminate\View\Middleware\ShareErrorsFromSession::class
my api/posts was on the api middleware thats why there's no session shared whatsoever.
also this link helped solved this.
Laravel 5.2 $errors not appearing in Blade
You are passing Request object in the validator. You need to change the validation code a bit:
$this->validate(request()->all(), [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
Read more in the docs.
You can validate this way
$this->validate($request, [
'title' => 'required|unique:posts,title|min:3',
'body' => 'required'
]);
I hope this will work.
Here the signin function is working fine but $this->validate() function returns nothing in view page. tried various method suggested in other Q&As. seems something wrong with helpers.
userController
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'bail|required',
'password' => 'required'
]);
if (Auth::attempt([ 'email' => $request['email'], 'password' => $request['password'] ])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
Login Page
#if ($errors->any())
<div>
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form name="loginForm" action="{{ route('signin') }}" method="post" autocomplete="disable">
<div class="form-group mb-4">
<input type="email" class="form-control {{ $errors->has('email')? 'is-invalid' : ''}}" name="email" aria-describedby="emailHelp" placeholder=" " />
<label for="loginFormInputEmail">Email address</label>
</div>
<div class="form-group mb-4">
<input type="password" class="form-control {{ $errors->has('password')? 'is-invalid' : ''}}" name="password" placeholder="Password" />
<label for="loginFormInputPassword">Password</label>
</div>
Probably another issue would be with $errors not being saved to Session variable $errors and nothing being shown in the view.
Here is an example of the same issue: http://laravel.io/forum/03-28-2016-errors-variable-empty-after-failed-validation
For me the solution defined in the above link worked. Solution: Is in app\Http\Kernel.php Move \Illuminate\Session\Middleware\StartSession::class, from $middlewareGroups to $middleware
Before
After
Source Thrade
: Laravel MessageBag errors array is empty in view but with content if I kill script
My Laravel blog project the get method of postcontroller is working but post method is not working. I redirect The Post Method. But Accordind to my my code it should return to my Admin page.My Controller Code is
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Category;
class PostController extends Controller
{
public function getBlogIndex() {
return view('frontend.blog.index');
}
public function getSinglePost($post_id,$end='frontend') {
return view($end . '.blog.single');
}
public function getCreatePost() {
return view('admin.blog.create_post');
}
public function postCreatePost(Request $request ) {
$this->validate($request, [
'title' => 'required|max:120|unique:posts',
'author' => 'required|max:80',
'body' => 'required'
]);
$post = new Post();
$post->title = $request['title'];
$post->author = $request['author'];
$post->body = $request['body'];
$post->save();
return redirect()->route('admin.index')->with(['success' => 'Post Successfully Created']);
}
}
My Routes file
<?php
Route::group(['middleware' => ['web']], function () {
Route::group([
'prefix' =>'/admin'
], function() {
Route::get('/', [
'uses' => 'AdminController#getIndex',
'as' => 'admin.index'
]);
Route::get('/blog/posts/create', [
'uses' => 'PostController#getCreatePost',
'as' => 'admin.blog.create_post'
]);
Route::get('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
});
});
My form is
#extends('layouts.admin-master')
#section('styles')
{!! Html::style('src/css/form.css') !!}
#endsection
#section('content')
<div class="container">
#include('includes.info-box')
<form action="{{ route('admin.blog.post.create') }}" method="post">
<div class="input-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" {{ $errors->has('title') ? 'class=has-error' : '' }} value="{{ Request::old('title') }}">
</div>
<div class="input-group">
<label for="author">Author</label>
<input type="text" name="author" id="author" {{ $errors->has('author') ? 'class=has-error' : '' }} value="{{ Request::old('author') }}">
</div>
<div class="input-group">
<label for="category_select">Add Category</label>
<select name="category_select" id="category_select">
<option value="Dummy Category ID">Dummy Category</option>
</select>
<button type="button" class="btn">Add Category</button>
<div class="added-categories">
<ul></ul>
</div>
<input type="hidden" name="categories" id="categories">
</div>
<div class="input-group">
<label for="body">Body</label>
<textarea name="body" id="body" rows="12" {{ $errors->has('body') ? 'class=has-error' : '' }} >{{ Request::old('body') }}</textarea>
</div>
<button type="submit" class="btn">Create Post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
#endsection
#section('scripts')
{!! Html::script('src/js/posts.js') !!}
#endsection
When I submit My post I shows this
I dont find where the problem is. Plz Help Me
This is an extremely common error and a good one to look out for. Whenever you see:
MethodNotAllowedHttpException in RouteCollection.php
The very first thing you should check is your routes file to make sure you have Route::get or Route::post correctly based on what you are trying to do.
Your issue is that your form sends the data as POST, but your route is GET.
<form action="{{ route('admin.blog.post.create') }}" method="post">
and
Route::get('/blog/post/create', [
'uses' => 'PostController#postCreatePost',
'as' => 'admin.blog.post.create'
]);
Change that to Route::post for it to function correctly.
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);
}
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