0
votes

I have some routes in my Laravel application (many routes)

I want to add new functionality, to return all data in JSON format. Now data are just views .

/route1/options /route2/options

etc

i want to have

/json/route1/options /json/route2/options

so, if any my existent route gets a prefix /json then data should be returned with JSON .

My routes looks like normal routes in Laravel

Route::get('user/{id}', function($id) {

    $user = ....
    return view('userprofile', $user);
});

How to change this to know that json format is requested? should it be separate routing group where each route is described again?

2

2 Answers

0
votes

In my eyes the best way to achieve this would be to allow the client to choose what they want. This is typically achieved using the Accept header.

GET myapp.com/user/1 HTTP/1.1
Accept application/json

This method is good when writing applications in Laravel as the request object is always informed if JSON is requested via the Accept header.

I've used Laravel 5.2's implicit model binding in the following examples.

Route::get('user/{user}', function(Request $request, User $user) {

    if ($request->wantsJson()) {
        return response()->json($user);
    }

    return view('userProfile', $user);
});

This method avoids putting unnecessary information in the url keeping your API clean. However a route that many go down (myself included) is to separate routes that return data and routes that return views.

Route::get('user/{user}', function(Request $request, User $user) {
    // Standard route, return a view
});

Route::get('api/user/{user}', function(Request $request, User $user) {
    // API route, always return JSON
});
0
votes

Assuming Laravel 5.2:

https://laravel.com/docs/5.2/routing#parameters-optional-parameters

Route::get('user/{id}/{format?}', function($id, $format = null) {

    $user = ....

    if($format == 'json') {
        return response()->json($user);
    }

    return view('userprofile', $user);
});