Reputation: 5672
I'm using a custom request class for laravel form validations.
This is my request class
class ContactUsRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'lname' => 'required'
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'lname.required' => 'please enter the last name'
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
And this is where I call it,
public function send(ContactUsRequest $request) {
$validator = $request->validated();
if ($validator->fails()) {
return redirect('/contactus')
->withErrors($validator)
->withInput();
} else {
ContactUs::create($request->all());
return redirect('/contactus');
}
}
But when I input correct values I get this,
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to a member function fails() on array
Upvotes: 0
Views: 1945
Reputation: 4813
Using form request classes
If validation fails, a redirect response will be generated automatically to send the user back to their previous location. The errors will also be flashed to the session so they are available for display. If the request was an AJAX request, a HTTP response with a 422 status code will be returned to the user including a JSON representation of the validation errors.
In order to capture validation failure you may use the Validator facade
E.g
use Illuminate\Support\Facades\Validator;
//...
public function send(Request $request) {
$validator = Validator::make($request->all(), [
'lname' => 'required'
// ...
]);
if ($validator->fails()) {
return redirect('/contactus')
->withErrors($validator)
->withInput();
}
ContactUs::create($request->all());
return redirect('/contactus');
}
Form Request Validation Documentation
Manually Creating Validators Documentation
And we can keep ContactUsRequest like this.
public function send(ContactUsRequest $request) {
$validator = $request->validated();
ContactUs::create($request->all());
return redirect('/contactus');
}
Upvotes: 1
Reputation: 2069
That's because request object automatically do that for you and you don't need to redirect back manually and $validator
variable contains validated inputs
so in your case you don't need to do anything and you can remove if
and redirect safely
public function send(ContactUsRequest $request) {
ContactUs::create($request->validated());
return redirect('/contactus');
}
}
Upvotes: 1