Laravel request validation doesn't show error messages - laravel

After I used group middleware, I am not able to access error messages. Error bags returns empty.
There was no problem before.
I have researched, some users have solved the problem by changing http/kernel.php
\Illuminate\Session\Middleware\StartSession::class, $middlewareGroups to $middleware.
However, It doesn't work for me.
Also $validated = $request->validated(); function doesnt returns validation error. In my CreditcardRequest Class I have attributes, messages, rules functions. If validation fails these messages needs to be shown.
previously When validated(); method was running on the controller, it was showing the messages if the form is empty. I have 20 pages all of them working, before middleware grouping.
Creditcard Blade
<div class="messages">
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Error!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
</div>
CreditcardRequest
public function attributes()
{
return [
'cc_name' => 'CC Owner',
..
];
}
public function messages()
{
return [
'required' => 'Required: :attribute',
...
];
}
public function rules()
{
return [
'cc_name' => 'required|max:128',
];
}
Controller
public function doPaySection(CreditcardRequest $request)
{
$validated = $request->validated();
$cc = TRUE;
if ($cc):
return redirect('/pay_success')->with('success', 'success');
else:
return redirect('/pay_error')->with('error', 'error');
endif;
}
web.php
Route::group(['middleware' => ['client.role:guest']], function () {
Route::get('/login', 'HomepageController#showLogin')->name('login');
Route::post('/login', 'HomepageController#doLogin');
Route::post('/register', 'HomepageController#doRegister');
Route::get('/register', 'HomepageController#showRegister')->name('register');
});
login.blade
#if ($errors->any())
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Hata!</h3>
#foreach ($errors->all() as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif
Controller
public function doLogin(Request $request)
{
if (auth()->guard('client')->attempt(['email' => request('email'), 'password' => request('password')])) {
return redirect()->intended('/');
} else {
return redirect()->back()->with('error', 'error');
}
}

Can you try using this header in your request. Especially if you are hitting from postman.
Accept:application/json
Before using this, i was getting csrf token in case of invalid requests.

The code you have at the minute won't add a message to the $errors MessageBag, it will simply add a value to the session called error.
If you want to add an error to the message bag you could simply throw a ValidationException which redirect back with that message:
public function doLogin(Request $request)
{
if (auth()->guard('client')->attempt($request->only('email', 'password'))) {
return redirect()->intended('/');
}
throw ValidationException::withMessages([
'error' => 'The error message',
]);
}
Don't forget to import ValidationException with:
use Illuminate\Validation\ValidationException;

Your will be able to get in session('error')from below
return redirect()->back()->with('errors', 'error');
So your code would be like
#if (session('errors'))
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-warning alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h3 class="alert-heading font-size-h4 font-w400">Hata!</h3>
#foreach (session('errors') as $error)
<p class="mb-0">{{ $error }}</p>
#endforeach
</div>
</div>
</div>
#endif

Related

How to check username and password match laravel 7

I am creating the simple login form using laravel 7.i want to check the username and password match.it is a match redirect the home. if it does not redirect the login page again show the error username or password does not match. I tried the below code I got the error Call to undefined method App\User::attempt()
Login Controller.
public function check(Request $request)
{
$uname = $request->uname;
$password = $request->password;
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
if (User::attempt(array('uname' => $uname , 'password' => $password ))){
return "success";
}
else {
return "Wrong Credentials";
}
}
view Login
#extends('layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Login</h2>
</div>
<div class="pull-right">
</div>
</div>
</div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="row">
<form action="{{ route('login.check') }}" method="POST">
#csrf
<div class="col-sm-4">
<div class="left">
<strong>UserName</strong>
<input type="text" name="uname" class="form-control" placeholder="UName">
</div>
<div class="left">
<strong>Password</strong>
<input type="password" class="form-control" name="password" placeholder="Password"></textarea>
</div>
</br>
<div class="left">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
Model User
protected $fillable = [
'name', 'email', 'password',
];
you need to replace User::attempt with auth()->attempt
another thing you don't need to check uname and passowrd manually laravel do that for you inside the attempt method so it would be more efficient if
you delete those two lines
$user = User::where('uname',$a)->get()->last();
$pass = User::where('password',$b)->get()->last();
finally, depends on your User model you have name not uname so you need to update it like this
if (auth()->attempt(array('name' => $uname , 'password' => $password ))){
return "success";
} else {
return "Wrong Credentials";
}

How in laravel-livewire set flash message with validation erros

With laravel 7 /livewire 1.3 app in login form I got errors on invalid form with code:
public function submit()
{
$loginRules= User::getUserValidationRulesArray();
$this->validate($loginRules);
and shows error message near with any field
I want on login fail to add flash message and reading at
https://laravel.com/docs/7.x/validation
I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect()->to('/login');
}
I got flash message, but validation errors for any field is lost.
If I try to make :
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return redirect('/login')
->withErrors($validator)
->withInput();
}
and I got error :
Method Livewire\Redirector::withErrors does not exist.
in routes/web.php I have :
Route::livewire('/login', 'login')->name('login');
MODIFIED :
In component app/Http/Livewire/Login.php :
<?php
namespace App\Http\Livewire;
use App\User;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
use Auth;
use DB;
use App\Config;
use Cartalyst\Sentinel\Laravel\Facades\Sentinel;
class Login extends Component
{
public $form= [
'email'=>'admin#mail.com',
'password'=> '111111',
];
private $view_name= 'livewire.auth.login';
public function submit()
{
$request = request();
$loginRules= User::getUserValidationRulesArray('login');
$validator = Validator::make($request->all(), $loginRules);
if ($validator->fails()) {
session()->flash('danger_message', 'Check your credentials !');
return;
// return redirect()->to('/login');
}
$user = Sentinel::findByCredentials(['email' => $this->form['email']]);
if (empty($user)) {
session()->flash('danger_message', 'User "' . $this->form['email'] . '" not found !');
...
and template resources/views/livewire/auth/login.blade.php :
<article >
#include('livewire.common.alert_messages')
<form class="form-login" wire:submit.prevent="submit">
<div class="card">
#if ($errors->any())
Check your login credentials
#endif
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<div class="card-body card-block">
<h3 class="card-header">
<span class="spinner-border" role="status" wire:loading>
<span class="sr-only">Loading...</span>
</span>
Login
</h3>
<h4 class="card-subtitle">Use your credentials</h4>
<dl> <!-- email FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="email">Email:<span class="required"> * </span></label>
</dt>
<dd>
<input
wire:model.lazy="form.email"
name="email"
id="email"
class="form-control"
placeholder="Your email address"
autocomplete=off
>
#error('form.email')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dt> email FIELD DEFINITION -->
<dl> <!-- password FIELD DEFINITION -->
<dt>
<label class="col-form-label" for="password">Password:<span class="required"> * </span></label>
</dt>
<dd>
<input type="password"
wire:model.lazy="form.password"
id="password"
name="password"
class="form-control"
placeholder="Your password"
autocomplete=off
>
#error('form.password')
<div class="validation_error">{{ clearValidationError($message,['form.'=>'']) }}</div> #enderror
</dd>
</dl> <!-- <dl> password FIELD DEFINITION -->
</div> <!-- <div class="card-body card-block"> -->
<section class="card-footer row_content_right_aligned">
<button type="reset" class="btn btn-secondary btn-sm m-2">
Reset
</button>
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link">
Submit
</button>
</section>
</div> <!-- <div class="card"> -->
</form>
</article>
Which way is valid ?
Thanks in advance!
Before render method you can check if errorBag has items:
public function render()
{
if(count($this->getErrorBag()->all()) > 0){
$this->emit('error:example');
}
return view('livewire-component-view');
}
The beauty of Livewire is that you don't necessarily need to redirect to flash a message, you can display messages by setting properties on your component, and conditionally rendering them in your view. In this particular case, there's already logic readily available, you just have to check the errors-object being exposed by the validation.
In your view, all you have to do is check #if ($errors->any()) - if that's true, display your message. This is a Laravel feature, which Livewire implements. When any validation fails, an exception is thrown and intercepted, and the $errors variable gets exposed to your view. This means that whenver you do $this->validate(), and the validation fails, you can access the errors within $errors.
<div>
#if ($errors->any())
Check your login credentials
#endif
<form wire:submit.prevent="submit">
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<input type="password" wire:model="password">
#error('password') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Submit</button>
</form>
</div>
Use the $rules attribute to declare the rules, validate those rules with $this->validate() and Livewire will do most of the work for you. You do not need to return any redirects, or use session()->flash(). The session-state will not be flashed, because you don't perform a new page load.
class Login extends Component
{
public $form = [
'email' => 'admin#mail.com',
'password' => '111111',
];
protected $rules;
private $view_name = 'livewire.auth.login';
public function submit()
{
$this->rules = User::getUserValidationRulesArray('login');
$this->validate();
// No need to do any more checks, $errors will now be updated in your view as the exception is thrown
// Proceed with submitting the form

Error while submitting form Laravel 5.6

I have code in router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code in UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
return view('admin.add-user')->withInput();
}
}
Code in AddUserRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'required|same:pass1',
];
}
}
Code view errors:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
When running the path: http://localhost/LBlog/public/admin/manage-user/add and submit (Do not enter form information), the screen returns error: The page has expired due to inactivity. Please refresh and try again.
I hope someone can help me with this issue
That error appears due to CSRF token.
Add csrf token in your form.
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
#csrf
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>

Laravel Flash errors - How to check if a checkbox is checked?

I'm trying to do flash messages in Laravel, now the flash messages work for success messages and error messages on pages that don't have checkboxes.
I have a view called 'deleteappointmentform' which requires the user to check a checkbox and it deletes the checked appointments, however if I don't check any checkbox and click submit it gives me a success message without actually checking if they've checked and checkboxes. I'm trying to get it to display an error message if they don't check any checkboxes
Any help's appreciated, thanks
This is the function that deals with deleting appointments
function deleteAppointment(Request $request)
{
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled successfully!');
return redirect('all');
}
This is my messages blade
#if (Session::has('successCancelAppointment'))
<div class="alert alert-success" role="alert">
<strong>Success: </strong> {{Session::get('successCancelAppointment')}}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger" role="alert">
<strong>Errors:</strong>
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
This is my deleteappointmentsblade
#extends('layouts.master')
#section('title', 'Cancel Appointment')
#section('content')
<form action="{{url('deleteappointment')}}" method="POST">
{{ csrf_field() }}
#foreach ($appointments as $appointment)
<div>
<label> {{$appointment->user->firstname}} {{$appointment->user->surname}}</label>
<label>Has an appointment at: {{$appointment->time}}</label>
<label>On: {{$appointment->date}}</label>
<label>With Dr: {{$appointment->doctor->surname}}</label>
<input type='checkbox' value='{{$appointment->id}}' name='appointments[]'/>
</div>
#endforeach
<input type="submit" name="submitBtn" value="Cancel Appointments">
</form>
#endsection
you can try this
function deleteAppointment(Request $request)
{ $rules=array(
'appointments'=>'required'
);
$validator = Validator::make($request->all(), $rules);
if($validator->fails())
{
$messages = $validator->messages();
$errors = $messages->all();
return redirect()->back()->withErrors($errors);
}
Appointment::destroy($request->appointments);
Session::flash('successCancelAppointment', 'Appointment cancelled
successfully!');
return redirect('all');
}

validation message not showing in laravel 5.3

I am using validation in laravel 5.3. but error message not getting displayed. what to do?
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=>'required|min:2',
'address'=>'required',
'email'=>'required',
'contact_number'=>'required',
'date_of_birth'=>'required',
'company_name'=>'required',
'country'=>'required',
'city'=>'required',
'fax'=>'required',
'telephone'=>'required',
'picture_upload'=>'required',
]);
}
in view
#foreach ($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
I usually use FromRequests for validation, but I'm pretty sure that the validator takes the Request object, but you are passing it an array $request->all(), simply change that to: $request
Do like this :
In Controller
$this->validate($request, [
'name'=>'required|min:2',
'address'=>'required',
'email'=>'required',
'contact_number'=>'required',
'date_of_birth'=>'required',
'company_name'=>'required',
'country'=>'required',
'city'=>'required',
'fax'=>'required',
'telephone'=>'required',
'picture_upload'=>'required',
]);
In View
#if (count($errors) > 0)
<div class="alert alert-danger alert-dismissible fade in" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<strong>OOPS! You might have missed to fill some required fields. Please check the errors. <strong>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Resources