Laravel validation not working after submit - laravel

This did not show the errors after submit
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
$this->validate($request,[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
Inserting values into the database.I want to validate on submitting the form
public function store(Request $request)
{
//
$this->validate($request->all(),[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
I displayed errors like this, but not working for me
#if(count($errors) > 0)
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif

Add this piece of code on your controller method.
return back()->withErrors()->withInput()
you can also access old input value with old(field_name)

Use ->all() here to provide all input value in to validate
$this->validate($request->all(),[
Or you can try like this
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
And display error as
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

first, edit your method like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
use Validator;
and inside this method please edit your redirect route and make sure your redirect url, redirect you in the page that had the error message:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
if ($validator->fails()) {
return redirect(route('make your route here '))
->withErrors($validator)
->withInput();
}
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
and for displaying error messages inside your blade template make this :
#if(!empty($errors))
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
#endif
#endif

Related

Laravel : On 5.5 validation message not showing on view.blade

Validation not showing any message on view page. I just can't figure out.
My controller code
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules()); // checking validation
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
Here is my model code for validation check :
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
On view page didn' get any validation message : On my view
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div> #endif
Also added in a app/exceptions/handler.php file code
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
Not working at all.what am i missing ?
Try using -
#if (session()->has('error'))
<div class="alert alert-danger">
<ul>
<li>{{ session('error') }}</li>
</ul>
</div>
#endif
In this way you can access only the key, that has been set by with methods
Change this line:
$this->validate($request, Country::rules());
To:
$request->validate(Country::rules());

laravel pass validation error to custom view

I created a validation but cant show it on view, its important to return search view and don't redirect back user. help me please, thanks all?
Controller :
public function search(Request $request)
{
$msg = Validator::make($request->all(), [
'search' => 'required'
]);
if ($msg->fails()) {
return view('layouts.search')->withErrors($msg->messages());
} else {
return "Thank you!";
}
}
View :
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error}} </li>
#endforeach
</ul>
#else
You can use $error->first('name_of_error_field') to show error messages.
You can do it like this:
public function search(Request $request)
{
$validator = Validator::make($request->all(), [
'search' => 'required'
]);
if ($validator->fails()) {
return view('layouts.search')->withErrors($validator); // <----- Send the validator here
} else {
return "Thank you!";
}
}
And in view:
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error->first('name_of_error_field')}} </li>
#endforeach
</ul>
#endif
See more about Laravel Custom Validators
Hope this helps

Laravel 5.2.26 get form validation data array

I submit the form and have some validation mean email,require,unique email,
when validation have error message then laravel 5.2 return validation return array.
I guess you want to retain the submitted data on error.
Considering a sample
public function postJobs(Request $request) {
$input = $request->all();
$messages = [
'job_title.required' => trans('job.title_required'),
];
$validator = Validator::make($request->all(), [
'job_title' => 'required'
], $messages);
if ($validator->fails()) { // redirect if validation fails, note the ->withErrors($validator)
return redirect()
->route('your.route')
->withErrors($validator)
->withInput();
}
// Do other stuff if no error
}
And, in the view you can handle errors like this:
<div class="<?php if (count($errors) > 0) { echo 'alert alert-danger'; } ?>" >
<ul>
#if (count($errors) > 0)
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
#endif
</ul>
</div>
And if you want the input data, you need to redirect with ->withInput(); which can be fetch in view like:
Update
<input name= "job_title" value="{{ Request::old('job_title') }}" />
But, the best thing is to use laravel Form package so they all are handled automatically.
If you just need form data, you can use Request object:
public function store(Request $request)
{
$name = $request->input('firstName');
}
https://laravel.com/docs/5.1/requests#accessing-the-request
Alternatively, you could use $request->get('firstName');
Use old() to get previous value from input. Example:
<input name="firstName" value="{{old('firstName')}}">
See documentation here https://laravel.com/docs/5.1/requests#old-input

Form issue in Laravel 5

In the routes.php
Route::get('/form1', 'FriendsController#getAddFriend');
Route::post('/form1', 'FriendsController#postAddFriend');
In the app/Http/Controllers/FriendsController.php
namespace App\Http\Controllers;
use App\Http\Requests\FriendFormRequest;
use Illuminate\Routing\Controller;
use Response;
use View;
class FriendsController extends Controller
{
public function getAddFriend()
{
return view('friends.add');
}
public function postAddFriend(FriendFormRequest $request)
{
return Response::make('Friend added!');
}
}
In the app/Http/Requests/FriendFormRequest.php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class FriendFormRequest extends Request
{
public function rules()
{
return [
'first_name' => 'required',
'email_address' => 'required|email'
];
}
public function authorize()
{
return true;
}
public function forbiddenResponse()
{
return Response::make('Permission denied foo!', 403);
}
public function response()
{
}
}
In the resources/views/friends/add.blade.php
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
<form method="post">
<label>First name</label><input name="first_name"><br>
<label>Email address</label><input name="email_address"><br>
<input type="submit">
</form>
when i run by http://localhost/laravel/public/form1
I am getting error as "Whoops, looks like something went wrong."
When I remove the following line
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
It displays the form
What is the error?
What I can think of is that your $errors variable is not existing and that's what causes the script to throw an exception.
1. If you are using Laravel 5.2 you might find your answer here:
Undefined variable: errors in Laravel
Basically in in app/Http/Kernel.php you need to check if $middlewareGroups['web'] contains
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
2. If you are using another Laravel version, probably you can add an additional check like this:
#if(isset($errors))
#foreach ($errors->all() as $error)
<p class="error">{{ $error }}</p>
#endforeach
#endif
To further investigate the problem you need to give us the stack trace of the exception. If you only see the "Whoops ..." message, then go in you .env file and change APP_DEBUG = true

Laravel validator returns $error as empty and old input also not coming

Here is My Code:
Model(User.php)
public static function validate($data)
{
return validator::make($data, static::$rules);
}
Route
Route::post('sign_up',['as'=>'sign_up','uses'=>function(){
$validate = App\User::validate(Input::all());
if($validate->fails())
{
return Redirect::back()->with_errors($validate)->withInput();
}
dd(Input::all());
}]);
View:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Here iam getting errors as empty and also i am missing my old inputs
Which version of laravel framework you are using ?
once replace this line of code :-
return Redirect::back()->with_errors($validate)->withInput();
with this following code and give a try:-
return Redirect::back()->withErrors($validate)->withInput();

Resources