@JarekTkaczyk thank you for including me in the list of the legends :) . But, I am kind of in the same boat as you here. Currently working on a simple content sharing application that allows users like: add links to content, comments and votes and things like that. For handling ajax calls it uses same routes as for non-ajax calls and return the html in both cases ( and some messages in case of ajax ) . On the client site I am completely relying on the Http status codes for error handling to keep the json response simple for example this is what I have inside the Base Controller :
abstract class Controller extends BaseController {
use ValidatesRequests;
/**
* layout to be used with this controller
* @var string
*/
protected $layout = '';
/**
* creates a json representation of the view
* @param string $view
* @param array $viewData
* @return JsonResponse
*/
protected function jsonResponse($view = null, $viewData = [], $mergeData = [])
{
$jsonData = [];
if($view)
{
$jsonData['html'] = view($view,$viewData)->render();
if(($data = array_shift($viewData)) instanceof Paginator)
{
$jsonData['next_page_url'] = $data->nextPageUrl();//for infinite scroll and load more functionality.
}
}
//merging any extra data to the final JSON response.
//this may include success and error messages.
$jsonData = array_merge($jsonData,$mergeData);
return new JsonResponse($jsonData);
}
/**
* creates the view response for the controller
* @param string $view
* @param array $viewData
* @param array $layoutData
* @return Response
*/
protected function viewResponse($view, $viewData = [], $layoutData = [])
{
if($this->layout)
{
return view($this->layout, $layoutData)->nest('content',$view, $viewData);
}
return view($view,$viewData);
}
}
And a sample controller action for updating or deleting a posted link to some content looks like this: ( the app is not over-engineered)
/**
* saves the updated record
* @param Request $request
* @return Response
*/
public function processEditLinkForm(LinkFormRequest $request)
{
$link = $this->link->findOrFail($request->id);
$link->update($request->only('url','title','description'));
if($request->ajax())
{
return $this->jsonResponse('link.link',compact('link'),[
'message' => 'Link updated successfully!'
]);
}
//here redirect back otherwise.
}
/**
* deletes the link record from database
* @param Request $request
* @return Response
*/
public function deleteLink(LinkFormRequest $request)
{
$this->link->findOrFail($request->id)->delete();
if($request->ajax())
{
return $this->jsonResponse(null,[],[
'message'=>'Link Deleted successfully!'
]);
}
//redirect back otherwise
}
In case of ajax call my responses would look like this:
{
html: "<...........> .....</>",
message: "usually a success message for crud success"
}
//or as simple as:
{ message: "deleted successfully!" }
I am still looking for a better solution.
Usman.