Skip to content

Instantly share code, notes, and snippets.

@jdavidbakr
Created May 22, 2015 13:08
Show Gist options
  • Save jdavidbakr/ffd3a50d390232837031 to your computer and use it in GitHub Desktop.
Save jdavidbakr/ffd3a50d390232837031 to your computer and use it in GitHub Desktop.
Laravel: Controller for JSON processor
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Foundation\Bus\DispatchesCommands;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController {
use DispatchesCommands,
ValidatesRequests;
protected $force_json = false;
/**
* Overriding this to wrap the errors into an ajax_form compatible response
*
* @param \Illuminate\Http\Request $request
* @param array $errors
* @return \Illuminate\Http\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors) {
if ($this->force_json || $request->ajax() || $request->wantsJson()) {
$error_list = array();
$field_list = array();
foreach ($errors as $field => $messages) {
$error_list[] = implode("\n\n", $messages);
$field_list[] = $field;
}
$final_message = "The following error" . (count($error_list) > 1 ? "s are" : " is") . " in your submission:\n\n" . implode("\n\n", $error_list);
$array = array(
'message' => $final_message
);
return new JsonResponse($array, 200);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
/**
* buildRedirect will either send a regular redirect
* or send a redirect back in a json response
*
* @param |Illuminate|Http|Request $request
* @param string $target
* @return |Illuminate|Http|Response
*/
protected function buildRedirect(Request $request, $target) {
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse(array('redirect' => $target), 200);
}
return redirect()->to($target);
}
/**
* sendMessage will send back a message
*
* @param |Illuminate|Http|Request $request
* @param string $message
* @return |Illuminate|Http|Response
*/
protected function buildMessage(Request $request, $message) {
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse(array('message' => $message), 200);
} else {
throw new UnauthorizedHttpException("You cannot access this resource directly. Please verify that JavaScript is enabled in your browser.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment