handle $errors and old input with 2 forms in a single page - laravel

I'm using laravel 5.2.
I'm trying to have 2 similar forms in one single page, one for registering, and one for logging in.
The problem is after some validation error, i can't recognize which one of the two was submitted to place some errors display and fill the correct form with the old input.
I had the idea of trying sending an hidden variable with the forms to recognize which one of the two was used, but when i get back to the forms page i can't retrieve the old('hidden_field').
I also tried to get the path of the referer page to check if i could recognize them from it, but it doesn't work.
Any different idea for a solution??

I. Deal with old input
- Make 1 attribute with different name in those 2 forms. So you can use old() normally
II. Deal with $errors. Use named error bag
- In your Controller
public function postRegister(Request $request){
$validator = Validator::make($request->all(), $array_rules);
if ($validator->fails()){
return redirect('url')->withErrors($validator, 'form_register');
}
}
public function postLogin(Request $request){
$validator = Validator::make($request->all(), $array_rules);
if ($validator->fails()){
return redirect('url')->withErrors($validator, 'form_login');
}
}
- In your view
//Access each form's errors normally
$errors->form_login->all()
$errors->form_register->all()
// Use old input normally
old('name_register');
old('name_login');
Hope this help you.

Thanks to a suggestion in the comments, i found out i had to add a validation rule to my hidden input field in order to pass it again to the view, and get the value with the old() method.
I could use it then to recognize which one of the two forms has been used.

Related

laravel request return message keys translations

I have a Laravel Application and another APP making calls via API to Laravel. These 2 projects are separated.
Laravel and App have their own multilanguage system. They work independently but uses the same key translations.
So my idea was that all Laravel responses must be translations key, like: 'messages.success'.
With this response, the App can translate it.
All of these are working fine.
The problem appeared when I started working with Laravel Requests for validating forms.
In this case, the validation errors are automatically translated so the App receives the response translated with the default language of the Laravel application.
So what can I do?
I thought with 2 ideas but I don't know if they can work.
1: Passing the language into params. Don't know if it can work, how can I set the language before Laravel validates the Request?
2: Override the functionality of Requests to return messages without translate, so instead of "Felicidades" return "messages.success". I really like this approach. But how can I do it for all the rules? Overriding the messages function like this:
public function messages()
{
return [
'unique' => 'validation.unique'
];
}
For every rule works... but I feel bad.
Another approaches?
What is the best way to fix this problem?
I would suggest that you use this hacky solution in 2 lines of code. Go to /resources/lang/{code}/validation.php. You can see that it returns an array of messages by default. Modify it like so:
// Replace return in the first line
$ret = [
/* all the translations go here as normal */
];
// Add this as the last line. This will replace all values with their keys.
return array_combine(array_keys($ret), array_keys($ret));
After that you can use validation as per usual and you'll get validation message keys instead of messages. Cheers and hope this helps.

Codeigniter cannot validate the variable

valueWhen I want to validate posted value in Codeigniter, I do it in the following way:
$this->form_validation->set_rules('name', 'Name','required|xss_clean|strip_tags|trim|max_length[50]|alpha');
But I cannot understand how can I do the same validation for $name variable if it is grabbed from url like this:
$name = end($this->uri->segment_array());
I tried to do this and then validate in the same way
$this->form_validation->set_value('name', $name);
but validation did not pass. Could you please help me.
Technically we refer to this particular validation library as Form Validation which works on form data.
There are other methods such as using route files (which is a perfect tool in CI) that you can take advantage of for URL checking.
Beside any already-developed tools (like uri-validator), you can write your own validating functions.

Single method to handle post or loading view in laravel

I am trying to understand how POST routing will work. I have a method defined, signup(), and I want to use the same method to detect if the user wants to sign up (so load the signup view) or if the user already in the signup view (form) and posting his details to register.
Can this be done in one function in laravel? if yes, then how? Is this controlled by Routes and if yes, can someone please clarify this with an example?
Laravel documentation is really confusing for beginners.
Thanks in advance,
While this is possible but it's not recommended way to do that, you should keep your routes separated from each other (using GET and POST) and should use different methods as well. Basically any form submission should use POST request (using POST HTTP method) and to show the form just use a GET method but anyways, you can do it (what you have asked for) like this way:
// Declare the route
Route::post('signup', 'UserController#signup');
Now in your signup check for the submit button to make sure that, the form is submitted, so if the input submit is available in the $_POST array then the form is submitted otherwise, it's not submitted but an empty form was presented to the user or a failed validation redirect happened. Maybe something like this:
public function signup()
{
if(Input::has('submit')) {
// It's a submission, so Validate submitted Form data
// if invalid then redirect back with inputs and errors
// Otherwise save it
}
else {
// show the form
return View::make('user.signup');
}
}
Don't do it
This is just an idea but, it's a bad idea, just think about what happens if you have errors on your form and you want to redirect back then the whole thing would become messy, the controller method will become totally unmanageable after a while because it does many things while it should have only one specific responsibility.
I have this practical experience, because, I used to think that, if I can use one function for loading and saving and even also updating then it would be smart but to be honest it was stupid and obviously it's an anti-pattern, not the best practice, against KISS (Keep It Simple Stupid) principle. This kind of coding is a bad idea and you'll suffer for it in future and you would not dare to touch the code thinking that if you brake anything because you'll be confused by your own code.
Just use separate methods to show a form and save submitted data, Also check this on slideshare.
Yes, you can use one route to do it:
Route::any('signup', 'SignupController#signup');
Or two routes pointing to the same url:
Route::get('signup', 'SignupController#getSignup');
Route::post('signup', 'SignupController#postSignup');
In both cases you'll need a controller:
Here it is with all related methods:
class SignupController extends Controller {
// This one is for Route::any()
public function signup()
{
if (Input::has('email'))
{
// create your user
}
return View::make('signup');
}
// those two are for the second option
public function getSignup()
{
return View::make('signup');
}
public function postSignup()
{
// create your user
}
}

Laravel-4 Empty PUT data being sent to a resourceful controller

G'day,
I'm having issues with PUT requests made via Chrome Postman to a controller, the PUT data is not present, POST data works fine.
I had performed a composer update prior to ensure that the latest version of vendor products where available and even removed bootstrap/compiled.php.
Is anybody else having similar issues?
The update function with both section_id and data being empty in the response:
public function update($id)
{
$section_id = Input::get('section_id');
$data = Input::all();
return Response::json(array('id' => $id, 'section_id' => $section_id, 'data' => $data));
}
I've debugged the code all the way to ParameterBag.php and $this->request's parameter list is empty, I'm not sure what's supposed to contain any values but all through the code the input values are empty. Not sure what to do now, short of using post instead of put.
PUT parameters don't work "out of the box" because PHP itself has some security restrictions around them. See: http://www.php.net/manual/en/features.file-upload.put-method.php
Laravel does implement a common workaround for this, though.
In Postman (or your form, or curl, or whatever client you're using), simply add a URL parameter name: "_method" value: PUT
Example 1:
?_method=PUT
Example 2:
<input type="hidden" name="_method" value="PUT" />
Laravel uses the symfony Http Foundation which checks for the _method variable and if it's present it routes based on its value, instead of the actual HTTP method used.
You have to send a POST request with adding an extra parameter _method with value PUT and it will works fine.

If codeigniter model returns 0 rows, display custom error message. How to extend to a general case?

I have a variety of functions within my models which serve a different purpose.
One for example looks up the data for a given $_GET variable in the URL string.
I am trying to work out a way of displaying an error message if there is no matching row in the database due to url string manipulation for example.
My first idea was simply to return an error message (if there is an error) with each call to the function, then simply have an if statement whereby if there is an error, an error view is shown, and if not the normal view is shown..
Problem with this is that this function is called numerous times in my controller, and other similar functions are called throughout my code which need similar error handling..
I dont want millions of similar if/else statements all over my code to handle errors..
Anyone got any better ideas?
Cheers
Use the flashdata item of the session class. You can concatenate error messages and put them in the flashdata item to display.
my_function(){
// code that determines if there is an error returns => $error
if ($error)
{
// concat previous and current errors
$new_error = $this->session->flashdata('errors') . $error;
// replace 'errors' with newly concatenated errors
$this->session->set_flashdata('errors', $new_error);
}
}
This will keep track of all errors generated through each request and allow you to display a "list" of errors for that particular request.
echo $this->session->flashdata('errors');

Resources