php - Laravel 5 return JSON or View depends if ajax or not -
i know if there magic method use scenario :
if call page via ajax request controller returns json object, otherwise returns view, i'm trying on controllers without changin each method.
for example know can :
if (request::ajax()) return compact($object1, $object2); else return view('template', compact($object, $object2));
but have lot of controllers/methods, , prefer change basic behavior instead of spending time change of them. idea ?
the easiest way make method shared between of controllers.
example:
this controller class other controllers extend:
<?php namespace app\http\controllers; use illuminate\routing\controller basecontroller; abstract class controller extends basecontroller { protected function makeresponse($template, $objects = []) { if (\request::ajax()) { return json_encode($objects); } return view($template, $objects); } }
and 1 of controllers extending it:
<?php namespace app\http\controllers; class mycontroller extends controller { public function index() { $object = new object1; $object2 = new object2; return $this->makeresponse($template, compact($object, $object2)); } }
Comments
Post a Comment