xTheWolf
xTheWolf

Reputation: 1886

Laravel Route for JSON Response Views

I have some views which return data of my Models with toJSON().

Is it possible (using 5.3) to make those unavaiable for normal users, but reachable for AJAX requests?

I've seen that there is an api.php routes-file but those seem to need the auth:api middlerwares, and I don't want them to need a api-key or something because the route is called by my application itself using twitter typeahead.

Upvotes: 0

Views: 433

Answers (2)

Gadzhev
Gadzhev

Reputation: 442

As @Mandeep Gill already mentioned you can check if the request is coming from ajax:

function myFunction() {
    if (!Request::ajax()) {
        return;
    }

    // Include logic here and define data
    $data = '';

    return response()->json($data, 200);
}

However, I'd suggest you to create a private API that your application can use.

Upvotes: 2

Mandeep Gill
Mandeep Gill

Reputation: 4895

Where you are returning result return like this :

if(\Request::ajax()) {

  return \Response::make(["data" => $data]); // return what you likes

} else {

  return view('test'); // For normal view not ajax request.

}

Upvotes: 1

Related Questions