laravel 5 return HTML or JSON depending on route

a 夏天 提交于 2019-12-22 11:30:53

问题


I want to show different output - JSON or HTML.

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

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.


回答1:


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 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.




回答2:


You can pass the prefix as a parameter, then handle your business in the action based on given prefix

REF: http://laravel.com/docs/5.1/routing#route-group-prefixes



来源:https://stackoverflow.com/questions/32573457/laravel-5-return-html-or-json-depending-on-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!