Reputation: 15
Recently I've upgraded Laravel 5.3
from Laravel 5.2
and after that I am finding several validation issues. One of the strange issue is with rule required_without
i.e. working fine with laravel 5.2.
The route
is:
Route::post('chats/create','ChatController@insertMessage');
Inside controller, I've defined the method insertMessage()
as:
public function insertMessage(Request $request){
$error = false;
$result = array();
$responsecode = 200;
$input = $request->all();
$validator = Validator::make(
array(
"patient_id" => $input["patient_id"],
"chat_id" => !empty($input["chat_id"]) ? $input["chat_id"] : null,
"sender_id"=> $input["sender_id"],
"image" => $request->hasFile('file') ? $request->file('file') : null,
"content" => !empty($input["content"]) ? $input["content"] : null
),
array(
"patient_id" => "required|exists:users,id,user_type,patient",
"chat_id" => "sometimes|nullable|exists:chats,id",
"sender_id"=>"required|exists:users,id",
"image" => "required_without:content|image",
"content" => "required_without:image"
)
);
if ($validator->passes()){
try {
DB::beginTransaction();
//Some operations
}
catch(\Exception $e){
//Some operations
}
}
//Finally return the response
return response()->json(array(
'error' => $error,
'input_data' => $result),
$responsecode
);
}
And the request I am making using post-man is as:
The request headers are Authorization
and a custom header
, no content-type
header is there. And the response
I am getting is:
{
"error": true,
"input_data": {
"error_message": "The image must be an image. "
}
}
Why it requires an image if content
field is present there in the request
data?
Using statement dd($input);
I can get the post data as:
array:4 [
"patient_id" => "3"
"content" => "Hello"
"sender_id" => "1"
"sender_name" => "System Admin"
]
Upvotes: 1
Views: 493
Reputation: 6710
You may use the validation rules as,
"image" => "nullable|required_without:content|image",
"content" => "nullable|required_without:image"
Since laravel 5.3
has nullable
rule, you may set it where your input value can be a null. Looking into your code, you're setting image
and content
as null
if not present in the request.
"image" => $request->hasFile('file') ? $request->file('file') : null,
"content" => !empty($input["content"]) ? $input["content"] : null
So finally your validator
should look like,
$validator = Validator::make(
array(
"patient_id" => $input["patient_id"],
"chat_id" => !empty($input["chat_id"]) ? $input["chat_id"] : null,
"sender_id"=> $input["sender_id"],
"image" => $request->hasFile('file') ? $request->file('file') : null,
"content" => !empty($input["content"]) ? $input["content"] : null
),
array(
"patient_id" => "required|exists:users,id,user_type,patient",
"chat_id" => "sometimes|nullable|exists:chats,id",
"sender_id"=>"required|exists:users,id",
"image" => "nullable|required_without:content|image",
"content" => "nullable|required_without:image"
)
);
Hope this helps!!
Upvotes: 1