0

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"}]}

2 Answers 2

1

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());
}
Sign up to request clarification or add additional context in comments.

Comments

0
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);
  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.