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);
}
Related
I use laravel 8 & have 3 table:
Products, ProductPrice & ProductsPublisher:
this is my Products model for this relationship:
public function lastPrice(){
return $this->hasMany(ProductPrice::class)->where('status','active')->orderBy('created_at','DESC')->distinct('publisher_id');
}
and this is my productsPrice model for publisher relationship:
public function getPublisher(){
return $this->belongsTo(ProductsPublisher::class,'publisher_id');
}
now, i want to use laravel resource for my api, i wrote products resource:
public function toArray($request)
{
return [
'id' => $this->id,
'price' => lastPrice::make($this->lastPrice),
'status' => $this->status,
'slug' => $this->slug,
'title' => $this->title,
'description' => $this->description,
'txt' => $this->txt,
'lang' => $this->lang,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
but in lastPrice resource, when i wrote like this:
return [
'id' => $this->id,
'main_price' => $this->main_price
];
it give me this error:
Property [id] does not exist on this collection instance.
when i use this code:
return parent::toArray($request);
get response but because i need to use another relationship in my lastPirce for publishers, i cant use that code and should return separately my data.
What i should to do?
thanks
Edit 1:
this is my Controller Code:
$products = Product::where('id',$id)->where('slug',$slug)->where('status','confirm')->first();
if(!$products){
return $this->sendError('Post does not exist.');
}else{
return $this->sendResponse(new \App\Http\Resources\Products\Products($products), 'Posts fetched.');
}
and this is sendResponse & sendError:
public function sendResponse($result, $message)
{
$response = [
'success' => true,
'data' => $result,
'message' => $message,
];
return response()->json($response, 200);
}
public function sendError($error, $errorMessages = [], $code = 404)
{
$response = [
'success' => false,
'message' => $error,
];
if(!empty($errorMessages)){
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
thanks.
Edit 2:
i change my lastPrice Resource toArray function to this and my problem solved, but i think this isn't a clean way, any better idea?
$old_data = parent::toArray($request);
$co = 0;
$new_data = [];
foreach ($old_data as $index){
$publisher_data = Cache::remember('publisher'.$index['publisher_id'], env('CACHE_TIME_LONG') , function () use ($index) {
return ProductsPublisher::where('id' , $index['publisher_id'])->first();
});
$new_data[$co]['main_prices'] = $index['main_price'];
$new_data[$co]['off_prices'] = $index['off_price'];
$new_data[$co]['publisher'] = SinglePublisher::make($publisher_data);
$new_data[$co]['created_at'] = $index['created_at'];
$co++;
}
return $new_data;
I have data, they look like this:
{
sender_name : "Real fake sender name",
recipient_name : "Real fake recipient name",
goods: [
{
"no" : 1
"name":"Pen",
"unit": "1",
"qty":"50",
"price":"50",
"amount":"2500",
"vat_percent":"5",
"vat_sum": "125",
"total_sum": "2625"
}
]
}
I need to validate "goods" using extend validator. Here is his code:
Validator::extend('invoiceGoods' , function($attribute, $value, $parameters, $validator) {
$rulesForGoods = [
'no' => 'integer|required',
'name' => 'string|max:64|required',
'unit' => 'required|integer',
'qty' => 'required|string',
'price' => 'required|numeric',
'amount' => 'required|numeric',
'vat_percent' => 'nullable|numeric',
'vat_sum' => 'nullable|numeric',
'total_sum' => 'required|numeric'
];
foreach ($value as $good) {
$validator = Validator::make($good , $rulesForGoods);
if ($validator->fails()) {
return false;
}
}
return true;
});
This is the main code.
$validator = Validator::make($data , [
'goods' => 'invoiceGoods',
'sender_name' => 'string',
'recipient_name' => 'string',
]);
if ($validator->fails()) {
return response()->json([
'success' => false,
'message' => 'Validation error.',
'data' => $validator->errors()
]);
}
If the goods validation error occurs, I get this answer:
But I would like to display errors like this: the wrong unit in the goods with no 1.
I know that the third argument can be passed an array with custom messages, but how to return it from the extended validator if it should return true or false?
https://laravel.com/docs/5.8/validation#custom-error-messages
$messages = [
'Validation.invoice_goods' => 'Errror message!',];
$validator = Validator::make($input, $rules, $messages);
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')
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
}
I need to do validation in one of my controllers — I can't use a request class for this particular issue — so I'm trying to figure out how to define custom validation messages in the controller. I've looked all over and can't find anything that suggests it's possible. Is it possible? How would I do it?
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// Can I create custom error messages for each input down here? Like...
$this->validate($errors, [
'title' => 'Please enter a title',
'body' => 'Please enter some text',
]);
}
You should have a request class like below. message overwrite is what you are looking for.
class RegisterRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'UserName' => 'required|min:5|max:50',
'Password' => 'required|confirmed|min:5|max:100',
];
}
public function response(array $errors){
return \Redirect::back()->withErrors($errors)->withInput();
}
//This is what you are looking for
public function messages () {
return [
'FirstName' => 'Only alphabets allowed in First Name',
];
}
}
This did it
$this->validate($request, [
'title' => 'required',
'body' => 'required',
], [
'title.required' => 'Please enter a title',
'body.required' => 'Please enter some text',
]);