Reputation: 9464
I have the following piece of code:
if(Request::ajax())
{
$response_values = array(
'validation_failed' => 1,
'errors' => $validator->errors->toArray()
);
return Response::json($response_values);
}
else
{
return Redirect::route("resource.create")
->withInput()
->withErrors($validator->errors);
}
I have this a lot in my code, and would like to find a way to automate this.
I tried creating a method in BaseController but it doesn't redirect properly, I also tried an after filter, but I was unable to pass parameters to this after filter, as I would need to pass errors and route.
How could I achieve this?
Upvotes: 1
Views: 907
Reputation: 87789
This is not working for you?
class BaseController extends \Controller {
public function processAndRedirectError($validator)
{
if(Request::ajax())
{
$response_values = array(
'validation_failed' => 1,
'errors' => $validator->errors->toArray()
);
return Response::json($response_values);
}
else
{
return Redirect::route("resource.create")
->withInput()
->withErrors($validator->errors);
}
}
}
class MyController extends BaseController {
public function store()
{
$validator = Validator::make(...);
return $this->processAndRedirectError($validator);
}
}
Upvotes: 3