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"}]}
User PHP
  • 13
  • 3

2 Answers2

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());
}
ApCo
  • 46
  • 5
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);
  
}
Mohamed Raza
  • 818
  • 7
  • 24