我想知道是否有一种神奇的方法可以使用这种情况:
如果我通过AJAX请求调用页面,控制器将返回一个JSON对象,否则它将返回一个视图,我试图在我的所有控制器上执行此操作而不更改每个方法。
例如,我知道我可以这样做:
if (Request::ajax()) return compact($object1, $object2);
else return view('template', compact($object, $object2));
但我有很多控制器/方法,我更喜欢改变基本行为,而不是花时间去改变所有这些。任何想法?
答案 0 :(得分:6)
最简单的方法是创建一个在所有控制器之间共享的方法。
这是所有其他控制器扩展的控制器类:
<?php namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
abstract class Controller extends BaseController
{
protected function makeResponse($template, $objects = [])
{
if (\Request::ajax()) {
return json_encode($objects);
}
return view($template, $objects);
}
}
这是扩展它的控制器之一:
<?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));
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
protected function makeResponse($request, $template, $data = [])
{
if ($request->ajax()) {
return response()->json($data);
}
return view($template, $data);
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController extends Controller
{
public function index(Request $request)
{
$object = new Object1;
$object2 = new Object2;
return $this->makeResponse($request, $template, compact($object, $object2));
}
}
答案 1 :(得分:1)
在laravel 5.1中,这是最好的方法:
if (\Illuminate\Support\Facades\Request::ajax())
return response()->json(compact($object1, $object2));
else
return view('template', compact($object, $object2));
&#13;
答案 2 :(得分:0)
@ryanwinchester建议的解决方案非常好。但是,我想将其用于来自update()
和delete()
的响应,并且自然而然地,最后return view()
并没有多大意义,因为您通常想使用{ {1}}。因此,我想到了这个主意:
return redirect()->route('whatever.your.route.is')