Laravel: How to log errors in form request input - laravel

I am using Laravel's form request to validate some complex input. If there is an error, Laravel returns the user to the previous page (which is fine), but I also want it to log the errors for me. How do I do that?
I attempted to use the form's withValidator method as follows, but got an error re 'maximum nesting level reached'.
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($validator->fails()) {
foreach($validator->errors()->all() as $error) {
logger($error);
}
}
});
}

Calling $validator->fails() in the after callback will end in an endless loop as it calls $validator->after() in the process. It re-evaluates and does not use a previous result.
Use $validator->errors() instead and check if it is empty.

Best way to validate on laravel is to use Laravel Request

As mentioned in the Laravel Documentation,
If the incoming request parameters do not pass the given validation rules, Laravel will automatically redirect the user back to their previous location.
In addition, all of the validation errors will be present in the $error variable.
The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.
To view the errors, you can add the following snippet inside your view which is returned when the validation is failed:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Related

Laravel broken translator (affects validation messages)

I have a problem with validation in Laravel. It used to work properly but now it does not. I do not know when the problem started.
The problem appears using the Validator class or a custom request file.
For example:
$validator = Validator::make($request->all(), [
'username' => 'required',
]);
If username is missing will produce an error bag containing the following error text:
validation.required
which is useless as far as validation feedback goes. If another field does not satisfy the minimum length, the error bag will contain:
validation.required
validation.min
Instead it should use the descriptions in the lang/en/validation.php file: 'The :attribute field is required.' i.e. 'The username field is required.'
It seems like the lang file is completely ignored. I checked it, and it contains a valid array. I don't know how to troubleshoot this. Can you please help?
I print out the errors as follows:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
</div>
#endif
Example of message bag as seen from the debugger:
UPDATE: I found the original cause of the problem.
# vendor/laravel/framework/src/Illuminate/Translation/Translator.php
public function get( ..
this function fails to retrieve the translated line.
Because the load() function fails to load the contents of lang/en/validation.php
Because it's looking for it in the wrong path (/resources/lang/).
Because there exists a /resource/lang folder, which was put there by a third party package (outdated, that was the path in laravel 8).
The problem was in fact with the translation subsystem.
It's been caused by a third party plugin which created a /resources/lang folder. This was the lang folder location in Laravel 8, and it still takes precedence over the new location /lang. But the necessary files were not there and the translation failed without raising any exception (!!!).
Removing the /resources/lang folder resolved my issue.

laravel POST request not rendering

Below is the auth part of my routes.
I just added the Tags part (where I can add another tag to the DB).
the tag creation works but the creation of a new post doesn't work now (worked before).
When I "submit" a post, it doesn't redirect or submits anything and it refreshes me back to the post create form with empty fields like nothing was rendered.
I tried to play with the positions of the routing, I made the post creation work but than the same happened to the tag creation where the page was "submiting" but actually there was no submit and it didn't redirect afterwards.
Auth::routes();
Route::get('/posts', 'PostsController#index')->name('posts.index');
Route::middleware('can:isAdmin')->group(function () {
Route::get('/posts/create', 'PostsController#create')->name('posts.create');
Route::get('/posts/{post}/edit', 'PostsController#edit')->name('post.edit');
Route::put('/posts/{post}', 'PostsController#update');
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store');
});
Route::get('/posts/{post}', 'PostsController#show')->name('posts.show');
thanks in advance.
At first, in given configuration you have two routes for same method / URI combination, so one of them would be unreachable:
// here the first
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store'); // <-- here the second
Looks like your post form submit goes to the tags, than validation fails and it redirect you back to post create page. Do you display validation errors?
here is example - https://laravel.com/docs/5.8/validation#quick-displaying-the-validation-errors
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
If it refresh your page so probably it works but if it do not save your request to databse it means that your request not validate respect to table.
Use validation for understand the errors.

Session Flash Messages not showing anywhere despite coding

I am following strict practices as per 5.2 docs, yet the validation is driving me insane.
1) This is a code snippet that I have in the controller right after the $property->save(); function
Session::flash('success', 'property table filled');
Session::flash('errors', 'These are the errors');
etc
Second issue is that the Validate method, if there are errors, it reverts back to the Create Form Page, but instead of binding the existing data in the Fields, it wipes everything out, so that I have to start the Form from scratch. Besides, it does not display any error messages
public function store(Request $request){
$this->validate($request, array(
'country' => 'bail|required|max:100',
'region' => 'bail|required|max:100',
etc
According to the documentation, this alone should, in case of fail to pass, revert back to the Create method above (the one that shows the Form to Create the Post) and issue a set of errors.
Since I am using a Resource Controller, all of the Routes are included in one line, and also, all of the Controllers and stuff are inside the Web Middleware:
Route::group(['middleware' =>'web'], function(){
Route::auth();
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
Route::resource('property', 'PropertyController');
});
This is the flawless snippet I have in the partials which is included in the Layout, so that it will display messages (success or fail) for every page that has a session:
#if(Session::has('success'))
<div class="alert alert-success" role="success">
<strong>Success: </strong> {{Session::get('success')}}
</div>
#endif
<div class="row">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
If instead, the storing of the data in the table database was successful, it still won't echo out any success flash session message.
Question:
Were there any errors in the submitted data, why doesn't display anything and why does it empty me all of the fields. The effect of emptying the fields is the same thing that would happen not when you refresh the Page, (filled fields stay filled) but when you click and press in the URL box of the browser.
Well, this is one of the cases where you get the answer but you dont know exactly why it works.
While I already had the Resource Controller Method inside the Web Middleware in the routes file, it turns out that I did not have to place the (or rather it was not enough) this:
Session::flash('success', 'property table filled');
Session::flash('errors', 'Posting failed');
in the Property Controller (and then this controller inside the Web Middleware in the Routes File), but actually those two lines on their own right in there in th Routes File
Session::flash('success', 'property table filled');
Session::flash('errors', 'Posting failed');
This is so much so that if I remove them from the Controller, this still works, but if I remove them from the Routes File, it doesn't.

Laravel 4 Login Credentials mismatch does not send back error data

Everything is fine, Login, Validation, and Username/Password combination mismatch, except for the mismatch, it does not send back the data that I'm sending.
This is my code, and I've tried different login techniques, and same issue.
This is my blade page errors section:
<div id="formErrorDiv">
#if ($errors->has())
<h2>* Please check your errors.</h2>
#endif
#if (isset($mismatch))
<h2>* {{ $mismatch }}</h2>
#endif
</div>
while the $errors-has() for the fields' validation works perfectly, the $mismatch variable always turns out empty.
This is my controller login section:
if($auth){
return Redirect::intended('/');
} else {
//dd('auth else');
$mismatch = 'Login Credentials Error.';
return Redirect::route('account-sign-in')
->with('mismatch', $mismatch);
}
although when I use the dd('auth else') it does work, and so it enters the else section but always sends nothing with the redirection.
You need to use Session::get() to retrieve the value you pass with with():
#if(Session::has('mismatch'))
<h2>* {{ Session::get('mismatch') }}</h2>
#endif
errors is the exception here. Because it's very common to pass that to the next view, Laravel built it in so the errors variable from the session is automatically available in your views...

Laravel 4 view composers not working

I saw this question. I have a similar problem, but it ain't working. Laravel 4 public functions.
I have a view composer that includes some codes in base layout. Here's my composer:
View::composer(array('common.menu_addition','common.base_errors','common.view_special'), function($view)
{
if(Auth::check()) {
$roles = Auth::user()->type;
if ($roles == '5') {
$view->with('roles', $roles);
} else {
return Redirect::to('news/index');
}
}
});
When I'm not logged in, it works perfectly. But one of my files of view composer goes like this:
<div class="pull-right">
#if (Auth::check())
#if ($roles == 5)
<ul class="nav">
<li>
<a href="{{ URL::to('admin/dash') }}">
<i class="icon-eye-open">
</i>
<strong>
Admin Dashboard
</strong>
</a>
</li>
</ul>
#endif
#endif
</div>
When I login, it won't display any site. It just says Undefined variable: roles in that view composer file.
I don't think it's possible to return a redirect like that, in your view composer. And even if you could it's a bad place to put that logic. You should create a filter http://four.laravel.com/docs/routing and redirect away if the user doesn't have the proper authentication level.
It looks like you're not defining $roles beforehand and not passing $roles into your views.
When you're making checks against the $roles in views you need to make sure that variable actually exists. Other possibility is to change the check to something like
#if (isset($roles) && $roles == 5)
to ignore the error but that gets really messy in the long run.
So make sure to initialise view variables beforehand in the view composer and everywhere else. Laravel tries to be much more stricter about non-initialised variables than PHP in common.

Resources