laravel 5根据路线返回HTML或JSON [英] laravel 5 return HTML or JSON depending on route

查看:308
本文介绍了laravel 5根据路线返回HTML或JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想显示不同的输出-JSON或HTML.

I want to show different output - JSON or HTML.

我不能使用\Request::ajax()功能,因为我只是收到普通请求(JSON响应不是基于XHR-Requests).

I cannot use the \Request::ajax() feature as I just get normal request (JSON response is not based on XHR-Requests).

是否有可能通过不同的路线来区分输出?例如.检查控制器是否被前缀为"mob"的路由调用,然后基于该路由为输出创建开关?

Is there perhaps a possibility to distinguish the output by different routes? E.g. check if the controller is called by a route with the prefix "mob" and then create a switch for the output based on that?

app/Http/routes.php:

Route::group( ['prefix' => 'api'], function(  ) {

  Route::resource( 'activation', 'ActivationController' ); 
  //...
} 

Route::group( ['prefix' => 'mob'], function(  ) {

  Route::resource( 'activation', 'ActivationController' ); 
  //...
} 

app/Http/Controllers/ActivationController:

<?php namespace App\Http\Controllers;

use App\Activation;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
class ActivationController extends Controller {

public function index()
{
    $activation = Activation::all(  );

    // switch to decide which output to show, based on the routes...
    if ($prefix == "mob") {
      return response()->view('template', compact($activation)); // not sure if it works this way
    } else {          
      return response()->json($activation);
    }

}

//...

我愿意寻求务实而简单的解决方案.一定不是路由解决方案,而是我不必更改太多代码的方法.

I am open for pragmatic and easy solutions. Must not be the routes-solution, but a way where I do not have to change much code.

推荐答案

您可以使用接受通配符/占位符的Request :: is()方法. 因此,您可以执行以下操作:

You can use the Request::is() method that accepts wildcards/placeholders. So you can do something like:

if($request->is('mob/*')) {
    // do your mob response
} else {
    // do the other response
}

如果每次执行响应时都具有此功能,则可以编写一个处理if的自定义响应宏,然后将数据作为数组并将其作为json返回或将其提供给刀片视图.

If you have this everytime you do a response than you can write a custom response macro that handles the if and just take the data as an array and return this as json or give this to your blade view.

这篇关于laravel 5根据路线返回HTML或JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆