How to check for required fields in object? - php

i have example object with fields
name => John
surname => Dow
job => engineer
and output form with placeholders. some required, some not.
what is best practice for check if it requred and show error with null fields?

There are multiple ways actually you can do that inside of controller method or make use of Laravels Request Classes for me I prefer to use Request Classes
look below I will list the two examples
Validate inside the controller's method
public function test(Request $request){
if($request->filled('name){
/*filled will check that name is set on the current
request and not empty*/
//Do your logic here
}
}
Second way is by using the Validator Facade inside your controller
use Validator;
class TestController{
public function test(Request $request){
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
/*continue with your logic here if the request failed on
validator test Laravel will automatically redirect back
with errors*/
}
}
Third way my favorite one personally
you can generate a Request class using this command
php artisan make:request AddBookRequest
that will generate the request class under "app/Http/Requests/AddBookRequest" , inside of any generated request class you will find two methods authorize() and rules()
in the authorized method you have to return truthy or falsy value this will detect if the current user making the request has authorization to fire this request inside of the rules method you do pretty much as you did in the Validator in the second way check the example
public function authorize(){
return true;
}
public function rules(){
return [
'title' => 'required|string',
'author_id' => 'required|integer'
];
}
then simply in your controller you can use the generated request like this
use App\Http\Requests\AddBookRequest;
public function store(AddBookRequest $request){
/* do your logic here since we uses a request class if it fails
then redirect back with errors will be automatically returned*/
}
Hope this helps you can read more about validation at
https://laravel.com/docs/5.6/validation

I think "simple is the best", just through object and check if properties exists
Ref: property_exists
Example:
if (property_exists($object, 'name')) {
//...do something for exists property
} else {
//...else
}

Related

Call to a member function fails() on array

I have a problem with the laravel validation.
Call to a member function fails() on array
Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Call to a member function fails() on array"
Stacktrace:
`#0 Symfony\Component\Debug\Exception\FatalThrowableError in
C:\laragon\www\frontine\app\Http\Controllers\authController.php:37
public function postRegister(Request $request)
{
$query = $this->validate($request, [
'user' => 'string|required|unique:users|min:4|max:24',
'email' => 'email|string|required|unique:users',
'pass' => 'string|required|min:8',
'cpass' => 'string|required|min:8|same:pass',
'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
]);
if ($query->fails())
{
return redirect('/registrar')
->withErrors($query)
->withInput();
}
}
The error is because what the ->validate() method returns an array with the validated data when applied on the Request class. You, on the other hand, are using the ->fails() method, that is used when creating validators manually.
From the documentation:
Manually Creating Validators
If you do not want to use the validate method on the request, you may
create a validator instance manually using the Validator facade. The
make method on the facade generates a new validator instance:
use Validator; // <------
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$validator = Validator::make($request->all(), [ // <---
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
The ->fails() is called in the response of the Validator::make([...]) method that return a Validator instance. This class has the fails() method to be used when you try to handled the error response manually.
On the other hand, if you use the validate() method on the $request object the result will be an array containing the validated data in case the validation passes, or it will handle the error and add the error details to your response to be displayed in your view for example:
public function store(Request $request)
{
$validatedData = $request->validate([
'attribute' => 'your|rules',
]);
// I passed!
}
Laravel will handled the validation error automatically:
As you can see, we pass the desired validation rules into the validate
method. Again, if the validation fails, the proper response will
automatically be generated. If the validation passes, our controller
will continue executing normally.
What this error is telling you is that by doing $query->fails you're calling a method fails() on something (i.e. $query) that's not an object, but an array. As stated in the documentation $this->validate() returns an array of errors.
To me it looks like you've mixed a bit of the example code on validation hooks into your code.
If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the
proper error response will automatically be sent back to the user. In
the case of a traditional HTTP request, a redirect response will be
generated, [...]
-Laravel Docs
The following code should do the trick. You then only have to display the errors in your view. You can read all about that, you guessed it, in... the docs.
public function postRegister(Request $request)
{
$query = $request->validate($request, [
'user' => 'string|required|unique:users|min:4|max:24',
'email' => 'email|string|required|unique:users',
'pass' => 'string|required|min:8',
'cpass' => 'string|required|min:8|same:pass',
'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
]);
}

How can I declare a route and a controller method that explicitly expect two query parameters like this?

I am pretty new in Laravel and I have the following problem.
I have to declare a route that handle requests like this:
http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc
So this URL have to mantein this format (activate as resource and 2 query parameters in the form ?email and &token. This is not a REST URI. I need to use it in this way).
I need a route and a controller method that handle this kind of request.
I know that I can do something like this:
1) Into the routes/web.php file I declare a rout like this
Route::get('/activate','MyController#myMethod');
2) Into MyController I declare this method:
public function myMethod(Request $request) {
if(Input::has('email') && Input::has('token')) {
$email = $request->input('email');
$token= $request->input('token');
// DO SOMETHING USING $email AND $token
}
else {
// SHOW ERROR PAGE
}
}
But onestly I find it pretty horrible. I came from Java and using Spring framework I can specify in the mapping between the URL and the controller method that a method handle a request toward a resource and that to be handled some specific query paramer have to be passed. Otherwise (if these parameter are not present the HTTP GET request is not handled by the controller method).
I know that in Laravel I can do something like this using REST form of my URL, I think something like this:
For the route mapping:
Route::get('/activate/{email}/{token}', [ 'uses' => 'ActivationController#activate', 'as' => 'activate' ]);
And then the controller method will be something like this:
public function activate($email, $token) {
// $email would be 'myemail#gmail.com'
// $token would be 'eb0d89ba7a277621d7f1adf4c7803ebc'
// do stuff...
}
But I can't use this kind of URI in this case (as specified the URL pattern have to be in the format:
http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc
So I desire do something like this with this kind of URI. I don't wont to pass the Request $request object to my controller method and then extract the parameters from it but I want to have a controller method signature like this:
public function activate($email, $token) {
in which if all the expected parameters are not passed simply the request will not handled by this controller.
I prefer do it because for me is a neater approach (reading the controller signature another developer immediately know that this method is expecting).
And also because I want that malformed parameters are not handled by the method (so I can avoid to handle error cases like: the user not pass the 2 parameters).
How can I do something like this in Laravel? (if it is possible...)
This is certainly a strange request, because it defies a more traditional use of Laravel routing practices, but this should work for you:
In routes.php (Laravel < 5.3) or web.php (Laravel 5.4+):
Route::get('/activate', [ 'as' => 'activate', function()
{
return app()->make(App\Http\Controllers\ActivateController::class)->callAction('activate', $parameters = [ 'email' => request()->email, 'token' => request()->token ]);
}]);
So we are instantiating the ActivateController class and calling the method 'activate' which is the first argument, then supplying a list of parameters the method receives in the form of an array.
public function activate($email, $token)
{
echo "Email: $email"; // myemail#gmail.com
echo "Token: $token"; // eb0d89ba7a277621d7f1adf4c7803ebc
// do stuff
}
Now, provided you go to http://laravel.dev/activate?email=myemail#gmail.com&token=eb0d89ba7a277621d7f1adf4c7803ebc $email and $token will be the respective key query parameters.
Now, as for validating to ensure that data is present. You have to add another argument to your activate() method, unless you want to do it inline.
The best practice way:
Run php artisan make:request ActivateRequest
A new file called ActivateRequest will be created in app\Http\Requests. Open it up and make sure your authorize() method returns true like so:
public function authorize()
{
return true;
}
Next, in the rules() method there is an array. Add the following:
return [
'email' => 'required|email',
'token' => 'required',
];
If you want to supply your own validation messages to these rules, add a method below rules() called messages() Like so:
public function messages()
{
return [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
];
}
Then, back in ActivateController pull in your new FormRequest class at the top use App\Http\Requests\ActivateRequest; and use it in the method like so:
activate($email, $token, ActivateRequest $request) {
...
Now, your request will be validated and you don't even have to use the $request variable.
The inline (not so best practice way)
If you are dead set on not having an extra argument in your method, you can validate data in the controller like so:
First, bring in the Validator class at the top. use Validator;.
public function activate($email, $token)
{
$validationMessages = [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
];
$validation = Validator::make(request()->toArray(), [
'email.required' => 'You must supply an email address.',
'email.email' => 'That email is address is not valid.',
'token.required' => 'Please supply a token.',
], $validationMessages);
if ( $validation->fails() )
{
return 'Sorry, there was a problem with your request';
}
// do stuff
}
Hope this helps.

Using a CustomRequest for Form Validation in Laravel 5.1 fails?

I've created a custom Request called CustomerRequest that I want to use to validate the form fields when a new customer is created. I cannot get it to work, it appears to be continuing into the store() method even when it should fail.
I have three required fields: givenname, surname, email
Here is my CustomerRequest:
public function rules()
{
return [
'givenname' => 'required|max:3',
'surname' => 'required',
'email' => 'required|unique:customers,email',
];
}
Here is my CustomerController:
use pams\Http\Requests\CustomerRequest;
-----------------------------------------
public function store(CustomerRequest $request, Customer $customer)
{
$request['created_by'] = Auth::user()->id;
$request['modified_by'] = Auth::user()->id;
$customer->create($request->all());
return redirect('customers');
}
When I submit the form using a givenname of "Vince" it should fail because it is greater than 3 characters long, but instead I get this error:
FatalErrorException in CustomerController.php line 52: Cannot use object of type pams\Http\Requests\CustomerRequest as array
Line 52 in the controller is $request['created_by'] = Auth::user()->id;
From what I understand, if the CustomerRequest fails then the user should be redirected back to the customers.create page and not run the code contained in the store() method.
I found the problem.
CustomerRequest had:
use Request;
instead of:
use pams\Http\Requests\Request;
Now the validation passes and fails as expected.
From docs, in Form Request Validation:
All you need to do is type-hint the request on your controller method.
The incoming form request is validated before the controller method is
called, meaning you do not need to clutter your controller with any
validation logic
Solution would be if you use it like so:
CustomerController.php
use Illuminate\Http\Request;
// ...
public function store(CustomerRequest $customerRequest, Customer $customer,Request $request)
{
$request['created_by'] = Auth::user()->id;
$request['modified_by'] = Auth::user()->id;
$customer->create($request->all());
return redirect('customers');
}
So what you want to know is that FormRequest -- which you are extending in your custom request validator CustomerRequest.php -- is a bit different than request that resides in Illuminate\Http namespace.
actually, you may find out why if you run (with your old code) dd($request['created_by'] = Auth::user()->id);. you should get the word forbidden or maybe! an exception telling that it'is not instantiable. (in my case I got forbidden because I've tested it on 5.2 right now).
$request is object, use it like following
use pams\Http\Requests\CustomerRequest;
-----------------------------------------
public function store(CustomerRequest $request, Customer $customer)
{
$inputs = $request->all();
$inputs['created_by'] = Auth::user()->id;
$inputs['modified_by'] = Auth::user()->id;
$customer->create($inputs);
return redirect('customers');
}

What is the use of After Validation Hook in Laravel 5

I'm learning Laravel 5 and trying to validate if an email exists in database yet then add some custom message if it fails. I found the After Validation Hook in Laravel's documentation
$validator = Validator::make(...);
$validator->after(function($validator) use ($email) {
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
});
if ($validator->fails()) {
return redirect('somewhere')
->withErrors($validator);
}
but I don't really understand what this is. Because I can simply do this:
//as above
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
//redirect as above
It still outputs the same result. When should I use the 1st one to validate something instead of the 2nd one?
The point of the first method is just to keep everything contained inside of that Validator object to make it more reusable.
Yes, in your case it does the exact same thing. But imagine if you wanted to validate multiple items.
foreach ($inputs as $input) {
$validator->setData($input);
if ($validator->fails()) { ... }
}
In your case you will have to add that "if" check into the loop. Now imagine having to run this validation in many different places (multiple controllers, maybe a console script). Now you have this if statement in 3 different files, and next time you go to modify it you have 3x the amount of work, and maybe you forget to change it in one place...
I can't think of many use cases for this but that is the basic idea behind it.
By the way there is a validation rule called exists that will probably handle your emailExist() method
$rules = [
'email' => 'exists:users,email',
];
http://laravel.com/docs/5.1/validation#rule-exists
There may be many scenarios where you may feel it's requirement.
Just assume that you are trying to build REST api for a project. And you have decided that update request method will not have any required rule validation for any field in request (as there maybe many parameters and you do not want to pass them all just to change one column or maybe you do not have all the columns because you aren't allowed access to it) .
So how will you handle this validation in UpdatePostRequest.php class where you have put all the validation rules in rules() method as given in code.
Further more there may be requirement that sum of values of two or more request fields should be greater or less than some threshold quantity. Then what?
I agree that you can just check it in controller and redirect it from there but wouldn't it defeat the purpose of creating a dedicated request class if we were to do these checks in controllers.
What I feel is controllers should be clean and should not have multiple exit points based on validation. These small validation checks can be handled in request class itself by creating a new Rule or extending your own custom validation or creating after validation hooks and all of them have their unique usage in Laravel.
Therefore what you may want to to do here is create a validation hook where it's assigned is to check whether request is empty or not like the example given below
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
if (!$this->validateCaptcha()) {
$validator->errors()->add('g-recaptcha-response', 'invalid');
}
});
}
And here is the full example for it.
<?php
namespace App\Http\Requests\Posts;
use App\Helpers\General\Tables;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdatePostRequest extends FormRequest
{
public function authorize()
{
return auth()->user()->can('update-post', $this);
}
public function rules()
{
return [
'name' => ['string', 'min:3', 'max:255'],
'email' => ['string', 'email', 'min:3', 'max:255'],
'post_data' => ['string', 'min:3', 'max:255'],
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
});
}
}
Thanks..
passedValidation method will trigger if the validation passes in FormRequest class. Actually this method is rename of afterValidation method. See: method rename Commit
So you can do like
class RegistrationRequest extends FormRequest
{
/**
* Handle a passed validation attempt.
*
* #return void
*/
protected function passedValidation()
{
$this->merge(
[
'password' => bcrypt($this->password),
]
);
}
}

Laravel 5.1 - Custom validation language file

Is it possible to conditionally set a custom language file (e.g. resources/lang/en/validation_ajax.php) for a validation request? Just to be clear, I don't want to change the app language, just use another set of messages depending on the request origin.
When I make an ajax validation call I want to use different messages since I'm showing the error messages below the field itself. So there's no need to show the field name (label) again.
I know you can define labels on 'attributes' => [] but it's not worth the effort since I have so many fields in several languages.
I'm using a FormRequest (there's no manual call on the Controller just a type hint).
You can override the messages() method for a specific request (let's say login request). Let me show you: At first place, you need yo create a new custom Form Request, here we will define a custom message for email.required rule:
<?php namespace App\MyPackage\Requests;
use App\Http\Requests\Request;
class LoginRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function messages()
{
return [
'email.required' => 'how about the email?',
];
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => ['required', 'email'],
'password' => ['required', 'confirmed']
];
}
}
Only email.required rule message will be override. For password it will display the default message set at validation.php file.
Now, apply the form request at your controller function like a type hint:
class LoginController{
public function validateCredentials(LoginRequest $request){
// do tasks here if rules were success
}
}
And that is all. The messages() method is useful if you need are creating custom packages and you want to add/edit validation messages.
Update
If you need to carry the bag of messages on into your package's lang file then you can make the following changes:
At your package create your custom lang file:
MyPackage/resources/lang/en/validation.php
Add the messages keeping the same array's structure as project/resources/lang/en/validation.php file:
<?php
return [
'email' => [
'required' => 'how about the email?',
'email' => 'how about the email format?',
],
];
Finally, at your messages() method call the lang's line of your package respectively:
public function messages(){
return [
'email.required' => trans('myPackage::validation.email.required'),
'email.emial' => trans('myPackage::validation.email.valid'),
];
}

Categories