Error handling from external request class - laravel

In the login system I'm creating in Laravel (Version 5.2), the registration request is passed on to the RegistrationRequest class, which contains the validation logic like this:
public function rules() {
return [
"username" => "required|min:3|unique:users",
"password" => "required|min:6|confirmed",
"email" => "required|confirmed|email|unique:users",
];
}
which is then passed on to the postRegistration function:
public function postRegistration(RegistrationRequest $request) {
$this->user->username = $request->input('username');
$this->user->mail = $request->input('email');
$this->user->password = password_hash($request->input('password'), PASSWORD_DEFAULT);
$this->user->save();
$this->auth->login($this->user);
return redirect('/dashboard');
}
All kind of basic stuff, now the problem that I have is that I have no idea how to show an error when my username is for example 2 characters long.
I know that normally, I'd do
return redirect('/registration)->withInput()->withErrors(["errorHere" => "value"]);
but since the validation rules are external, I have no clue how to pass those to a view.
I searched some forums and the docs, but I couldn't find anything clear on it.
Is there a way to show these errors, preferably with the withInput() method?
Thanks.

As you can see from the Docs from laravel:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
EDIT: Didn't notice the author itself answered the question until I refreshed the page.

So exactly one minute after asking this, a friend messaged me and told me that i could just do the following:
#if (count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{ { $error } }</li>
#endforeach
</ul>
#endif

Related

Laravel validation not working after submit

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

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

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();

Laravel MessageBag errors array is empty in view but with content if I kill script

I am trying to return errors back to my view, this is part of my controller TestcategoryController
$rules =array(
'name' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
//process
if($validator->fails()){
return Redirect::to('testcategory/create')->withErrors($validator);
}
In the view testcategory/create if I try and output the errors like
#if($errors->any())
{{ $errors->first('name') }}
#endif
I get nothing. But if I {{dd($errors)}} I get
object(Illuminate\Support\ViewErrorBag)#91 (1) { ["bags":protected]=> array(1) {
["default"]=> object(Illuminate\Support\MessageBag)#92 (2)
{ ["messages":protected]=> array(1)
{ ["name"]=> array(1) { [0]=> string(27) "The name field is required." } }
["format":protected]=> string(8) ":message" } } }
The only way I am getting the errors is if I kill the script. What am I doing wrong?
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
If you get nothing in your case, than it means you have overridden your $errors object with something else or with empty object - check your code and data you pass to the views. Your code is perfectly valid and works good - I've tested it locally. Maybe, you passed empty $errors object to your subview, but in other views the correct object is used.
You need to use it like this:
{{ $errors->getBag('default')->first('name') }}
Route::group(['middleware' => ['web']], function() {
Route::get('/home', 'HomeController#index')->name('home');
});
Add middleware, and resolved..
I was having the same problem with Laravel 8.0
The only way I could solve this was by entering the error bags layer by layer until I got to the messages manually:
#if (count($errors->getBags()))
<div class="alert alert-danger">
<ul>
#foreach ($errors->getBags() as $bag)
#foreach ($bag->getMessages() as $messages)
#foreach ($messages as $message)
<li>{{ $message }}</li>
#endforeach
#endforeach
#endforeach
</ul>
</div>
#endif

Resources