I have a column input named Address, and how to check, if user input like null, 'null' and '' , the return response will be error. I have make it, but it not working.
This is my code:
$address = $request->input('address');
if ($address == null)
{
return response()->json(['message'=>'no data','success'=>0]);
}
elseif($address == '')
{
return response()->json(['message'=>'no data','success'=>0]);
}
elseif($address == 'null')
{
return response()->json(['message'=>'no data','success'=>0]);
}
else
//process
}
Check out laravel validation: here.
For example:
$request->validate([
'address' => 'required'
])
If you want to check if input is filled you can do this:
$request->filled('address')
Check docs for Retriving inputs.
in your case:
if(!$request->filled('address')){
return response()->json(['message'=>'no data','success'=>0]);
}
You may use the empty function, which would return FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE. This implies the following conditions considered as empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
Snippet for your reference:
$address = $request->input('address');
if(empty($address)){
return response()->json(['message' => 'no data','success' => 0]);
}
Use laravel Validation, for more information checkout laravel doc link
$validator = Validator::make($request->all(), [
'address' => 'required'
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors()->first()], 422);
}
use validation facades : https://laravel.com/docs/5.7/validation
use Illuminate\Support\Facades\Validator;
public function MyFunction(Request $request){
try {
$validator = Validator::make($request->all(), [
'address' => 'required',
]
);
if ($validator->fails()) {
$response=array('status'=>'error','errors'=>implode(',', $validator->errors()->all()));
return response()->json($response, 400);
}else{
// validation success
}
} catch (\Exception $e) {
$response=array('status'=>'error','result'=>0,'errors'=>'Internal Server Error');
return response()->json($response, 500);
}
}
}
Related
I have the code below which sends the password reset link and it works fine. What I want to do is show password reset link or token in response. (Yes, I know it's dangerous.)
$status = Password::sendResetLink(
$request->only('email'),
function ($user, $token) {
(\DB::table('password_resets')
->updateOrInsert(
['email' => $user->email],
[
'token' => md5($token)
]
))
? $user->sendPasswordResetNotification(md5($token))
: null;
}
);
if ($request->expectsJson()) {
if ($status === Password::RESET_LINK_SENT) {
return response()->json(['message' => __($status)], 200);
} else {
return response()->json(['message' => __($status)], 422);
}
}
return $status === Password::RESET_LINK_SENT
? back()->with(['status' => __($status)])
: back()->withErrors(['email' => __($status)]);
}
I changed the code as below but I am getting 500 Internal Server Error. What's wrong?
$status = Password::sendResetLink(
$request->only('email'),
function ($user, $token) use (&$token) {
(\DB::table('password_resets')
->updateOrInsert(
['email' => $user->email],
[
'token' => md5($token)
]
))
? $user->sendPasswordResetNotification(md5($token))
: null;
}
);
if ($request->expectsJson()) {
if ($status === Password::RESET_LINK_SENT) {
return response()->json(['message' => __($status), 'link' => md5($token)], 200);
} else {
return response()->json(['message' => __($status)], 422);
}
}
return $status === Password::RESET_LINK_SENT
? back()->with(['status' => __($status)])
: back()->withErrors(['email' => __($status)]);
}
One way would be like this:
$token = DB::table('password_resets')->latest('created_at')->first()->token;
You get the last record inserted in the table (by sorting created_at column) which is the latest password reset and you can get the token from that.
return response()->json(['message' => __($status), 'link' => $token], 200);
And you getting the 500 Server Error could be from the addition of use (&$token) in the second code. use is the way to use the variables out of the function scope in the function and you don't have any variable named $token (Don't confuse with the $token in the function). And you're using the use to use a function variable outside of its scope which won't work.
Also you could set APP_DEBUG to true (NOT IN PRODUCTION MODE) to see the reason for 500 error.
I have a method in parent class
Controller.php
public function invalidError($errors = [], $code = 422)
{
return response()->json([
'errors' => $errors
], $code);
}
I am passing this method the following:
if($validator->fails()) {
return $this->invalidError([
array('key' => 'Some key')
]);
}
When the response comes in the errors message is always empty array like the following:
{
"errors": []
}
What am I missing?
To get the errors array from a validator, use failed()
if($validator->fails()) {
return $this->invalidError($validator->failed());
}
If you wants the messages from the failed rules use messages()
if($validator->fails()) {
return $this->invalidError($validator->messages());
}
For more information, you can check the documentation
I have a Controller with a method like this
public function chargeWallet(Request $request, $wallet, $user)
{
try {
$data = $request->validate([
'charge' => 'required|integer',
]);
}catch (\Exception $e) {
dd($e);
}
return redirect(back());
}
As you can see I'm checking that the charge type must be integer.
Now I want to check if the data type of charge was integer, then do this:
if($data['charge'] == INTEGER)
flash()->overlay('Success!', 'Success Message', 'success');
So the question is, how to check the type of data in the Controller ? What should I write instead of INTEGER for checking $data['charge'] ?
you can use is_int($var) or is_integer($var). you can also use is_numeric($var) to check if the variable is a number or a numeric string.
if(is_int($data['charge']))
flash()->overlay('Success!', 'Success Message', 'success');
I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)
I have this code, the $vatValidator validates the vat number. The $validator validates other request data.
For example if the user dont insert a value for the name field it will appear a validation error:
{success: false,…} errors: {name: ["Fill all fields."]} success :
false
But if the user insert a invalid value for the vat no validation message appears because in the response the errors are empty:
{success: false, errors: []} errors :[]
Do you know how to show a message when the vat number is incorrect? A message like "Invalid vat".
$vatValidator = VatValidator::validateFormat($request->country . $request->vat);
$validator = Validator::make($request->all(), $rules, $messages);
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->fails() || $vatValidator == false) {
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
Full method:
public function storeInfo(Request $request, $id, $slug = null, Validator $validator){
...
$rules = [];
$messages = [];
if ($all) {
$rules["name.*"] = 'required|max:255|string';
$rules["surname.*"] = 'required|max:255|string';
}
$vatValidator = VatValidator::validateFormat($request->country . $request->vat);
$validator = Validator::make($request->all(), $rules, $messages);
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->fails() || $vatValidator == false) {
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
if ($validator->passes()) {
}
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
You could use a closure for the validation:
$rules['vat'] = [
function ($attr, $value, $fail) use ($request) {
if (!VatValidator::validateFormat($request->country . $request->vat)) {
$fail('Invalid vat.');
}
}
];
$errors = $validator->messages();
$errors->merge($vatValidator->messages())
variable $error contains all error messages