I'm trying to make validation of $id and $offer_id inside my function:
public function getMessagesForOffer($id, $offer_id)
{
$validator = Validator::make($request->all(), [
'id' => 'required|numeric',
'offer_id' => 'required|numeric',
]);
if ($validator->fails()) {
return response([
'status' => 'error',
'error' => 'invalid.credentials',
'message' => 'Invalid credentials'
], 400);
}
}
This is throwing an error: "message": "Undefined variable: request",
And I see that it's incorrect coded, how can I correct it to work with single elements when there is no request inside my function?
$request->all() would just return array, so you can also use array here, so instead of $request->all() you can use:
['id' => $id, 'offer_id' => $offer_id]
or shorter:
compact('id', 'offer_id')
Related
I am trying to validate the form using this way:
// Start validation
$validator = Validator::make($request->all(), [
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w+(\.\w+)+$/'],
'status' => 'required',
]);
// If validation is not sucessfull
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->withErrors($validator)
], 200);
} else {
....
}
If the validation is failed I want to get the error messages in the message key. How can I get the error messages ? Its showing me an error message:
Method Illuminate\Validation\Validator::withErrors does not exist.
You have to use a validator error like this
if( $validator->fails() ) {
return response()->json([
'success' => false,
'message' => $validator->errors()
], 200);
}
Or
$validator->errors()->all(); # as a Array
Try this, It will return proper validation message and check the validation on defined field.
$request->validate([
'project_token' => 'required',
'user_id' => 'required',
'competitor_name' => 'required',
'competitor_domain' => ['required','regex:/^(?!(www|http|https)\.)\w+(\.\w+)+$/'],
'status' => 'required',
], [
'project_token.required' => 'Please Generate Project token'
]);
in your blade file if you add this condition after each element then if any validation error acure then it will show in front with custom message
#if ($errors->has('project_token'))
<span class="text-danger">{{ $errors->first('project_token') }}</span>
#endif
I have below type of json in my laravel request, I want to validate json object key in my laravel request file. I want to validate title value is required of data json. I found solution but it's for controller, I want to validate it in my request file
{"ID":null,"name":"Doe","first-name":"John","age":25,"data":[{"title":"title1","titleval":"title1_val"},{"title":"title2","titleval":"title2_val"}]}
Why not use Validator
$data = Validator::make($request->all(), [
'ID' => ['present', 'numeric'],
'name' => ['present', 'string', 'min:0'],
'first-name' => ['present', 'string', 'min:0',],
'age' => ['present', 'numeric', 'min:0', 'max:150'],
'data' => ['json'],
]);
if ($data->fails()) {
$error_msg = "Validation failed, please reload the page";
return Response::json($data->errors());
}
$json_validation = Validator::make(json_decode($request->input('data')), [
'title' => ['present', 'string', 'min:0']
]);
if ($json_validation->fails()) {
$error_msg = "Json validation failed, please reload the page";
return Response::json($json_validation->errors());
}
public function GetForm(Request $request)
{
return $this->validate(
$request,
[
'title' => ['required'],
],
[
'title.required' => 'title is required, please enter a title',
]
);
}
public function store(Request $request)
{
$FormObj = $this->GetForm($request);
$FormObj['title'] = 'stackoveflow'; // custom title
$result = Project::create($FormObj); // Project is a model name
return response()->json([
'success' => true,
'message' => 'saved successfully',
'saved_objects' => $result,
], 200);
}
I've got basic laravel validator for my request:
$validator = Validator::make($request->all(), [
'speciality' => 'required|array|min:1',
]);
if ($validator->fails()) {
return response([
'status' => 'error',
'error' => 'invalid.credentials',
'message' => 'error validation'
], 400);
}
speciality should be an array, so I define it as required|array|min:1
The problem is when my request has an empty array with null inside: speciality: [ null ] and this somehow passes my validator.
How can I correct it to catch this case?
Using dot to access the underlying elements/values:
$validator = Validator::make($request->all(), [
'speciality' => 'required|array|min:1',
'speciality.*' => 'required' //ensures its not null
]);
See the Validation: Validating Arrays section of the documentation.
Notice that [null] in not an empty array, that's why your initial validation was passed. You can verify this doing:
dd(empty([null]));
This will output:
false
My route
Route::put('/users/{$id}', 'ApiController#profileUpdate')->name('user.update');
//profile update function
public function profileUpdate(Request $request){
try{
$validator = $this->validatorProfile($request->all());
if ($validator->fails()) {
$messages = $validator->messages();
return response()->json([
'status' => 400,
'error' => true,
'result' => false ,
'message'=> $messages,
'data' => []
]);
}
$id = $request->id;
$token = $request->header('authorization');
$user_id = JWTAuth::toUser($token)->id;
$user = User::find($user_id);
$data = $request->only('location','state','country','name');
$result = $user->profiles()->where(['user_id' => $$id])->update([
'location' => $data['location'],
'state' => $data['state'],
'country' => $data['country'],
]);
$result1 = $user->where(['id' => $user_id])->update([
'name' => $data['name'],
]);
return response()->json([
'status' => 200,
'error' => false,
'result' => true,
'message'=> "profile updated",
'data' => $data
]);
}
catch(Exception $e){
return response()->json([
'status' => 400,
'error' => true,
'result' => false,
'message'=> $e,
'data' => []
]);
dd($e);
}
}
Help me to find my mistake.
My url
http://localhost/project/public/api/v1/users/1
When i hit it on postman it give 404 error.
You will have to adjust your route parameter choice of naming. {$id} isn't going to work, but {id} will work just fine. Also the $$id reference in the code probably should be just $id.
As Alexey Mezenin has pointed out, it additionally would be good to add the $id parameter to your controller method to accept the route parameter.
Side Note:
When you are calling $request->id you are probably trying to get the route parameter, but that may not always return that. If there is any input in the Request named id that will be returned before a route parameter named id. It only tries to return a route parameter as a fallback.
$request->input('id') explicitly ask for an input named id.
$request->route('id') explicitly ask for a route parameter named id.
$request->id could be an input named id or a route parameter named id.
Since you're trying to pass ID, you need to add it as an argument. So, change this:
public function profileUpdate(Request $request)
To:
public function profileUpdate(Request $request, $id)
I'm trying to implement one of Laravel's new features "Custom Validation Rules" and I'm running into the following error:
Object of class Illuminate\Validation\Validator could not be converted to string
I'm following the steps in this video:
New in Laravel 5.5: Project: Custom validation rule classes (10/14)
It's an attempt Mailgun API's Email Validation tool.
Simple form that requests: first name, last name, company, email and message
Here is my code:
web.php
Route::post('contact', 'StaticPageController#postContact');
StaticPageController.php
use Validator;
use App\Http\Validation\ValidEmail as ValidEmail;
public function postContact(Request $request) {
return Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
}
ValidEmail.php
<?php
namespace App\Http\Validation;
use Illuminate\Contracts\Validation\Rule;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as Guzzle;
class ValidEmail implements Rule
{
protected $client;
protected $message = 'Sorry, invalid email address.';
public function __construct(Guzzle $client)
{
$this->client = $client;
}
public function passes($attribute, $value)
{
$response = $this->getMailgunResponse($value);
}
public function message()
{
return $this->message;
}
protected function getMailgunResponse($address)
{
$request = $this->client->request('GET', 'https://api.mailgun.net/v3/address/validate', [
'query' => [
'api_key' => env('MAILGUN_KEY'),
'address' => $address
]
]);
dd(json_decode($request->getBody()));
}
}
Expectation
I'm expecting to see something like this:
{
+"address": "test#e2.com"
+"did_you_mean": null
+"is_disposable_address": false
+"is_role_address": false
+"is_valid": false
+"parts": {
...
}
}
Any help is much appreciated. I've been trying to get this simple example to work for over two hours now. Hopefully someone with my experience can help!
In your controller
Try this:
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
// if valid ...
According to your route, the postContact method is the method to handle the route. That means the return value of this method should be the response you want to see.
You are returning a Validator object, and then Laravel is attempting to convert that to a string for the response. Validator objects cannot be converted to strings.
You need to do the validation, and then return the correct response based on that validation. You can read more about manual validators in the documenation here.
In short, you need something like this:
public function postContact(Request $request) {
$validator = Validator::make($request->all(), [
'firstname' => 'required|max:90',
'lastname' => 'required|max:120',
'company' => 'max:120',
'email' => [
'required', 'string', 'max:255',
new ValidEmail(new \GuzzleHttp\Client)
],
'message' => 'required',
]);
// do your validation
if ($validator->fails()) {
// return your response for failed validation
}
// return your response on successful validation
}