Passing Success or Failure For Laravel 4 Validation - php

I am in the middle of working with my create a user form inside of my restful user controller. While the user is on the form I have it currently posting to the store method. When the form is submitted to the method I want it to validate the user input and then redirect back to the create method for either displaying a success message or an array of error messages if there was a failure in the data validation. Can someone point out what is needed to help me redirect to the create method with either a success message or error message based off the validation test.
/**
* Store a newly created user in storage.
*
* #return Response
*/
public function store()
{
$input = Input::all();
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
$messages = $validator->all();
}
else
{
User::create([
'username' => $input['username'],
'email_address' => $input['email_address'],
'password' => $input['password'],
'role_id' => $input['role']
]);
}
return Redirect::to('users/create');
}

you could use either
$messages = $validator->messages();
or
$failed = $validator->failed();
to retrieve error messages. If you want show 'flash' message, you can use 'with' method in redirection.
Redirect::to('user/currentroute')->with('message', 'Something wrong');
for more details, you should read in documentation

Related

Laravel, Handling validation errors in the Controller

So i'm working on validating a form's inputs using the following code:
$request->validate([
'title' => 'bail|required|max:255',
'body' => 'required',
]);
So basically, there are two fields in the form, a title and a body and they have the above rules. Now if the validation fails I want to catch the error directly in the controller and before being redirected to the view so that I can send the error message as a response for the Post request. What would be the best way to do it?
I understand that errors are pushed to the session but that's for the view to deal with, but i want to deal with such errors in the controller itself.
Thanks
If you have a look at the official documentation you will see that you can handle the input validation in different ways.
In your case, the best solution is to create the validator manually so you can set your own logic inside the controller.
If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade.
Here a little example:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'bail|required|max:255',
'body' => 'required',
]);
// Check validation failure
if ($validator->fails()) {
// [...]
}
// Check validation success
if ($validator->passes()) {
// [...]
}
// Retrieve errors message bag
$errors = $validator->errors();
}
For someone who wants to know how to get validation errors after page redirection in the controller:
$errors = session()->get('errors');
if ($errors) {
//Check and get the first error of the field "title"
if ($errors->has('title')) {
$titleError = $errors->first('title');
}
//Check and get the first error of the field "body"
if ($errors->has('body')) {
$bodyError = $errors->first('body');
}
}
$errors will contain an instance of Illuminate/Contracts/Support/MessageBag
You can read more on the API here: https://laravel.com/api/8.x/Illuminate/Contracts/Support/MessageBag.html
Note: I have tested it in Laravel 8, it should work on Laravel 6+ if you get the MessageBag from the session

Getting the ErrorMessage Bag in Laravel Validation during Validation

As the question states. I am using the validation method where the Rules and Custom Messages are placed in the Http/Requests folder. However, I want to get the messageErrorBag in Laravel I don't have any problems if I am using the code below I can easily add my own variables to be passed together with the validator message bag.
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
However, if using the code below. I cannot do it since Laravel already handles the error return as per documentation.
public function store(StoreBlogPost $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
My question how can I do it? before it redirects back with the error message bag.? Is it possible
If you use StoreBlogPost in Controller , it automatically returns messages but if you want your messages in body of controller you should add validator to your controller body and use this code:
if ($validator->fails())
{
foreach ($validator->messages()->getMessages() as $field_name => $messages)
{
var_dump($messages); // messages are retrieved (publicly)
}
}
hope it helps

Adding items to the formRequest validator

I'm working on a project and one part of it is that users can create projects.
It is required for a project to be coupled to a user. If the user is logged in when creating a project, then there is no problem, i can just attach the project to the authenticated user, but when the user is not logged in, i have the following section in my form
In short, there are 2 radiobuttons, the 1st means "i have an account, log me in" with the login fields below it. The 2nd means "i'm a new user, create an account", which will show the correct fields to create a user.
Since this form is added to the project creation form, everything has to be validated at once.
Now i have a formRequest that handles all the validation, but i'm struggling with the login part.
When validating, i have to check the following things:
1) if the user was logged in when starting to fill in the form, but is no longer logged in when storing the data, then we have to add this to the errors array
2) if the user was not logged in when starting to fill in the form, and he choses to log in through the form a have explained above, then we need to try and log in the user when creating the project, and add a message to the errors array when the login fails "wrongs credentials has been supplied....".
I have tried with the following FormRequest:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateJobsRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
if (! auth()->check()) {
if($this->get('is_logged_in')) {
// If we reach this, then we were logged in when starting to fill in the form
// but are no longer when finishing the form (idle for to long, ....).
$this->getValidatorInstance()->errors()->add('authentication', 'You were no longer authenticated when creating the project.');
}
if($this->get('auth_type') == 'login') {
if(! auth()->attempt($this->getLoginParams())) {
// if we reach this, we have chosen to log in through the form, bu the provided details did not match our records.
$this->getValidatorInstance()->errors()->add('authentication', 'Failed to authenticate');
}
}
}
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'login.email' => 'required_if:auth_type,login',
'login.password' => 'required_if:auth_type,login',
'register.email' => 'nullable|required_if:auth_type,register|email|max:255',
'register.password' => 'required_if:auth_type,register,confirmed|max:255',
'register.firstname' => 'required_if:auth_type,register|max:255',
'register.name' => 'required_if:auth_type,register|max:255',
'jobs.*.title' => 'required',
'jobs.*.description' => 'required',
'jobs.*.category_id' => 'required|exists:job_categories,id',
'jobs.*.location_id' => 'required|exists:job_locations,id',
'jobs.*.profiles' => 'required|numeric'
];
}
private function getLoginParams()
{
return ['email' => $this->get('login.email'), 'password' => $this->get('login.password')];
}
}
The most important part is in the authorize method. I'm trying to add items to the errors array, but its not working.
1) If all the other validations from the rules function pass, then i am not redirected to the creation page but the code enters the controller and a project is created.
2) if not all other validations pass, then i'm redirected to the creation page, but the errors i added in the authorize method are not added to the errors, and thus not shown on the creation page.
I don't think the authorize method is the right place to put this logic.
I would add additional rules to the rules array based on the login status.
try something like this:
public function rules()
{
$rules = [
'login.email' => 'required_if:auth_type,login',
'login.password' => 'required_if:auth_type,login',
'register.email' => 'nullable|required_if:auth_type,register|email|max:255',
'register.password' => 'required_if:auth_type,register,confirmed|max:255',
'register.firstname' => 'required_if:auth_type,register|max:255',
'register.name' => 'required_if:auth_type,register|max:255',
'jobs.*.title' => 'required',
'jobs.*.description' => 'required',
'jobs.*.category_id' => 'required|exists:job_categories,id',
'jobs.*.location_id' => 'required|exists:job_locations,id',
'jobs.*.profiles' => 'required|numeric'
];
if (! auth()->check()) {
if($this->get('is_logged_in')) {
// If we reach this, then we were logged in when starting to fill in the form
// but are no longer when finishing the form (idle for to long, ....).
$rules = array_merge($rules, ['no_authentication' => 'required']);
}
if($this->get('auth_type') == 'login') {
if(! auth()->attempt($this->getLoginParams())) {
// if we reach this, we have chosen to log in through the form, bu the provided details did not match our records.
$rules = array_merge($rules, ['failed_authentication' => 'required', 'Failed to authenticate']);
}
}
}
return $rules;
}
public function messages()
{
return [
'no_authentication.required' => 'You were no longer authenticated when creating the project.',
'failed_authentication.required' => 'Failed to authenticate'
];
}

Loop through validation errors, and display the right one - Laravel 5.2

I have a registration system, and I need to display any validation errors that come up. Most of my validation is being checked by JavaScript because I'm using the Semantic-UI Framework. But there is 2 custom validation rules that I cant really display in the JavaScript, so I need to see which of those two error messages it is, and flash the correct error message.
Here is my Register function with the validation:
public function postRegister (Request $request) {
$validator = Validator::make($request->all(), [
'username' => 'unique:users',
'email' => 'unique:users',
'password' => '',
]);
if ($validator->fails()) {
flash()->error('Error', 'Either your username or email is already take. Please choose a different one.');
return back();
}
// Create the user in the Database.
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
'verified' => 0,
]);
// Flash a info message saying you need to confirm your email.
flash()->overlay('Info', 'You have successfully registered. Please confirm your email address in your inbox.');
return redirect()->back();
As you can see there are two custom error messages, and If a user gets just one of them wrong, it will flash my Sweet-alert modal with that message.
How can I maybe loop through my error message and see which one I get wrong, and display a specific flash message to that error?
To retrieve an array of all validator errors, you can use the errors method:
$messages = $validator->errors();
//Determining If Messages Exist For A Field
if ($messages->has('username')) {
//Show custom message
}
if ($messages->has('email')) {
//Show custom message
}

How do you flash Request data if a Validator fails in Laravel 5?

I've created a simple contact form in Laravel 5, using the Request object and a Validator object to check my input for errors.
The form in my view is coded in HTML, rather than the Laravel Form object, which isn't included by default in Laravel 5.
I need to set up my form so that if a validation rule fails, the user's input is flashed to the session so it doesn't disappear when the page redirects. I was able to accomplish this by putting a $request->flash() in the POST controller, before the validation code.
However, I do not want the data to be flashed (i.e, the form should be reset) if the validation passes and the form is successfully emailed. There's no apparent way for me to accomplish this in the $this->validate block, since Laravel helpfully handles the redirects automatically.
How can I tell Laravel to flash the form data ONLY if there is a validation error?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ContactController extends Controller
{
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
return view('contact');
}
/**
* Store a newly created resource in storage.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
// Flash current input in case the validator fails and redirects
$request->flash();
// Validate the form request, redirect on fail
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'subject' => 'required',
'message' => 'required|min:5',
]);
// Generate email from template and send
\Mail::send('emails.feedback',
array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'user_message' => $request->get('message'),
'subject' => $request->get('subject')
), function ($message) use ($request) {
$message->from(\Config::get('site.from_email'));
$message->to(\Config::get('site.contact_email'), 'Admin');
$message->subject(\Config::get('site.name') . ': ' . $request->get('subject'));
});
// Redirect to Contact route with success message
return \Redirect::route('contact')
->with('message', 'Thanks for contacting us!');
}
}
?>
If anybody like me didn't know how to get the old values and end up here somehow, here it goes:
<input value="{{ old('var_name') }}">
I don't see you needing to access the session data when Laravel provides you helpers like this.
Hope to have helped, have a nice day. =)
Just remove the following line of code:
$request->flash();
Laravel will take care of that for you by flashing the data on failed validation. The following method gets called on failed validation:
/**
* Create the response for when a request fails validation.
*
* #param \Illuminate\Http\Request $request
* #param array $errors
* #return \Illuminate\Http\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input()) // <-- Flashes inputs
->withErrors($errors, $this->errorBag()); // <-- Flashes errors
}
This is the trait used in your controller for validating the request and it's located at Illuminate/Foundation/Validation, name is ValidatesRequests. Check it to clarify yourself.
Alternatively, you may do it manually if you want for any reason, check the documentation.
To restore the old value if validation fails the entered data will display the view
value="{{ (old('title')) ? old('title') : $data->title}}

Categories