Validator in Laravel 5.6 not delivering $error messages - laravel-5.6

I am coding in Laravel 5.6 and i have a layout file called errors.blade with the contents of:
#if(session('status'))
<div class="alert alert-dismissible alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ session('status') }}
</div>
#endif
#if(count($errors))
<div class="alert alert-dismissible alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
#foreach($errors as $error)
<ul>
<li>{{ $error }}</li>
</ul>
#endforeach
</div>
#endif
And my controller that insterts data into db and uses the $this->validate is:
public function store()
{
$this->validate(request(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'username' => 'required',
'password' => 'required|confirmed',
'discord' => 'required'
]);
Admin::create([
'first_name' => request('first_name'),
'last_name' => request('last_name'),
'email' => request('email'),
'username' => request('username'),
'password' => bcrypt(request('password')),
'discord' => request('discord'),
]);
return redirect('/admin/login')->with('status', 'Install successfully completed. Use the form below to login to your account.');
}
As you can see i am sending back a session with the name of status which i have setup to show in my errors file, which works perfectly. But as soon as i leave a field blank or mismatch the passwords on purpose i get this from the actual $errors:
This is happening on all pages. I don't know what exactly is the problem. The status messages work, but the error message here doesn't work. It happens with any error with validator or even with the:
return redirect()->route('admin-login')->withErrors('Incorrect
Username or Password.');
Just a little more info, i am using a guard for admin and guard for the default laravel web to separate sessions of admin and regular users. I don't know if this could be any of the cause. Any help is greatly appreciated to remove this road block for me and any other users who have ran or may run into this.

Change the #foreach to this:
#foreach($errors->all() as $error)

Related

Using the redirect method, errors are not sent to view

When I use return view('login')->withErrors($validator->errors());, I get the errors returned if any. Now, if I use the Redirect method/class, it doesn't return the data.
I need to use redirect. I tested it in several ways, going through the different errors, but nothing works. I've read documentation, blogs and everything I do doesn't work.
I already tried return Redirect::back()->withErrors(['msg' => 'The Message']); and in the blade `{{ session()->get('msg') }}, but nothing .
I need some help as I have tried many things and nothing works.
Controller:
public function checkUserExists(Request $request)
{
$email = $request->input('email');
$validator = Validator::make(
$request->all(),
[
'email' => ['required', 'max:255', 'string', 'email'],
'g-recaptcha-response' => ['required', new RecaptchaRule],
],
$this->messages
);
if ($validator->fails()) {
// return view('login')->withErrors($validator->errors());
// return Redirect::back()->withErrors(['msg' => 'The Message']);
return Redirect::route('login')->withErrors($validator->errors());
// return Redirect::route('login')->withErrors($validator);
// return redirect()->back()->withErrors($validator->errors());
// return Redirect::back()->withErrors($validator)->withInput();
}
...
}
At the moment my bucket is just with this:
{{-- Errors --}}
#if ($errors->any())
<div class="alert alert-danger" role="alert">
<ul>
#foreach ($errors->all() as $key => $error)
<li>
{{ $error }}
</li>
#endforeach
</ul>
</div>
#endif
Version of Laravel: "laravel/framework": "^7.29",
try this code to pass the errors back to the view:
public function checkUserExists(Request $request)
{
$email = $request->input('email');
$validator = Validator::make(
$request->all(),
[
'email' => ['required', 'max:255', 'string', 'email'],
'g-recaptcha-response' => ['required', new RecaptchaRule],
],
$this->messages
);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
...
}
& in your view, you can access the errors using with:
{{-- Errors --}}
#if ($errors->any())
<div class="alert alert-danger" role="alert">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
this should work if your view is correct
and you are using the correct path to your view
in your redirect()->back() method

Default value selected in bootstrap button after logging out of app at login page

I want in my login form that when I logout of the app and redirect to login form page again, I want the office auto selected by default which i choose at the last time when logged in.
I am having the following button code in laravel login.blade.php
<input type="hidden" name="office_id" class="office_id" value="0">
<button type="button" class="btn btn-default office_name">Select Office</button>
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
#foreach($offices as $office)
<li>{{$office->name}}</li>
#endforeach
</ul>
</div>
These are the login and logout functions which I am using in loginController.php
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
'office_id' => 'required',
]);
if($user = User::where('email', $request->email)->get()->first()){
$office = Employee::with('office')->findOrFail($user->id);
$office_id = $office['office'][0]['id'];
if($request->office_id == $office_id){
if(Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
return redirect()->intended(route('admin.dashboard', compact('office_id')));
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Incorrect Password', 'The Message']);
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Select your office to log in', 'The Message']);
}
return redirect()->back()->withInput($request->only('email', 'remember'))->withErrors(['Invalid Email', 'The Message']);
}
public function adminLogout(){
Auth::guard('admin')->logout();
return redirect(route('admin.login'));
}
I believe you could achieve this with cookies. You set the time they stay active unlike the session.
Laravel has a cookie interface-
https://laravel.com/docs/5.5/requests#cookies
Cookies using PHP-
https://secure.php.net/manual/en/function.setcookie.php

Laravel 5.4 automatically redirec to home page when we use Validator

public function store(Request $request)
{
//this method will be called when we signup for members
$this->validate($request, [
'title' => 'required|max:255',
'body' => 'required',
]);
return 'success';
}
this will automatically redirected to homepage of Laravel without any exception
i need a validation message there
eg. title is required
Laravel has performed the redirect and stored the errors in the session. It is up to you to modify your view to display the errors that have been put in the session.
You can read more about displaying validation errors in the documentation here.
Code example from that link: (add this to 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.2: withErrors on redirect not working

I'm currently struggling with a Laravel problem I can't fix myself. If I pass errors using withErrors() the errors are not passed to the Error Bag ($errors).
My Controller (FormController):
public function contact(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all());
}
return redirect()->back();
}
The thing is, also withInput() is not working. Where could the problem come from? I appreciate your help!
(Part of) the defined routes.php:
Route::group(['middleware' => 'web'], function(){
Route::post('/contact', 'FormController#contact');
});
Session config
return [
'driver' => env('SESSION_DRIVER', 'memcached'),
'lifetime' => 120,
'expire_on_close' => false,
'encrypt' => false,
'files' => storage_path('framework/sessions'),
'connection' => null,
'table' => 'sessions',
'lottery' => [2, 100],
'cookie' => 'session',
'path' => '/',
'domain' => null,
'secure' => false,
];
In Laravel 5.2 you need to use the web middleware in your routes to pass the errors to the view.
Route::group(['middleware' => ['web']], function () {
Route::get('/', function() {
return view('welcome');
});
});
Don't pass anything to the withInput
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
}
and use the old function to get the flashed data
$name = $request->old('name');
or
{{old('name')}}
Hope it helps
If the controller that you are redirecting to is also using withErrors() function, the error messages in redirect()->back()->withErrors($validator) will be overwritten.
But, the old messages are still in session. So you can still read and display them with session('errors'):
#if ($errors->any())
<div class="alert alert-danger">
<ul class="my-0">
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#elseif (null !== session('errors') && session('errors')->any())
<div class="alert alert-danger">
<ul class="my-0">
#foreach (session('errors')->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
This can be due to session problem. To diagnose this problem use print_r($request->session()). if you are getting different id in session object that means session is not setting up properly.
To get it done open Kernel.php
dont specify below line in $middleware array
specify these below line in web middleware group and $middlewarePriority array
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,

Laravel flash message validation

I am creating a CRUD of books and what I wanted to do is like the generated auth files that if someone registers and didn't input any in the textbox, a flash message will return. I am doing that now in my crud but I can only make a flash message when a book is successfully created. This is my store function
public function store(Request $request)
{
$this->validate($request, [
'isbn' => 'required|',
'title' => 'required',
'author' => 'required',
'publisher' => 'required'
]);
Session::flash('msg', 'Book added!');
$books = $request->all();
Book::create($books);
return redirect('books');
}
And in my home.blade.php
#if(Session::has('msg'))
<div class="alert alert-success">
{{ Session::get('msg') }}
</div>
#endif
This actually works but I want to show some ready generated error flash when someone didnt complete fields. How can I do that?
It's pretty simple, first there's a sweet nice feature that is the redirect()->with()
So your controller code could be:
public function store(Request $request)
{
$this->validate($request, [
'isbn' => 'required|',
'title' => 'required',
'author' => 'required',
'publisher' => 'required'
]);
if(Book::create($books)){
$message = [
'flashType' => 'success',
'flashMessage' => 'Book added!'
];
}else{
$message = [
'flashType' => 'danger',
'flashMessage' => 'Oh snap! something went wrong'
];
}
return redirect()->action('BooksController#index')->with($message);
}
Then on your view:
#if (Session::has('flashMessage'))
<div class="alert {{ Session::has('flashType') ? 'alert-'.session('flashType') : '' }}">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{{ session('flashMessage') }}
</div>
#endif
Bonus you can put this on your footer, so the alerts boxes will vanish after 3 seconds:
<script>
$('div.alert').delay(3000).slideUp(300);
</script>
You could get the individual errors for a field
{!! $errors->first('isbn'); !!}
or you can get all the errors
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
you can use try catch like this
try{
$books = $request->all();
Book::create($books);
Session::flash('msg', 'Book added!');
}
catch(Exception $e){
Session::flash('msg', $e->getmessage());
}

Resources