Skip to content

Instantly share code, notes, and snippets.

@thepsion5
Last active February 29, 2020 15:27
Show Gist options
  • Save thepsion5/d7f43f183b500bb3afc5 to your computer and use it in GitHub Desktop.
Save thepsion5/d7f43f183b500bb3afc5 to your computer and use it in GitHub Desktop.
Example of using A Laravel Controller to automatically handle validation exceptions and auth failures
<?php
class BaseController extends Controller
{
public function callAction($method, $params)
{
$ajax = Request::isAjax();
try {
return parent::callAction($method, $params);
} catch(ValidationException $exception) {
return $this->handleValidationException($exception, $ajax);
} catch(AuthException $exception) {
return $this->handleAuthException($exception, $ajax);
}
}
protected function handleValidationException(ValidationException $exception, $ajax = false)
{
if($ajax) {
return Response::json(array('errors' => $exception->errors()), 422);
} else {
return Redirect::back()->withInput()->withErrors($exception->errors());
}
}
protected function handleAuthException(AuthException $exception, $ajax = false)
{
if(Request::isAjax()) {
return Response::json($exception->getMessage(), 403);
} else {
App::abort(403);
}
}
}
<?php
public class FooController extends BaseController
{
public function __construct(FooService $foos)
{
$this->foos = $foos;
}
public function store()
{
//throws ValidationException on failure
$foo = $this->foos->create(Input::all());
return Redirect::route('foos.show', $foo->id);
}
public function update($id)
{
//throws ValidationException on failure
//throws AuthException if the current user does not have access to a the relevant resource
$foo = $this->foos->findAndUpdate($id, Input::all());
return Redirect::route('foos.show', $foo->id);
}
}
@briedis
Copy link

briedis commented May 5, 2017

Nice snippet, thanks

@ziazon
Copy link

ziazon commented Aug 29, 2017

brilliant! been looking for a solution to not being able to catch the new $request->validate() style validation with Laravel 5.5. This works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment