How to design routes when dealing with Laravel API instead of returning Laravel views?

938 Views Asked by At

So far I've been building Laravel and Django apps that return views or templates from backend. So far so good.

However, I'm now building a Laravel API that gets called from a frontend AMP code.

In the old ways I do this in Laravel: From web.php

Route::get('/', function () {
    return view('welcome');
});

Or I can return the view from the controller.

However, if the Laravel app is an API that returns JSON, how can I design URLs?

Basically, if someone clicks a link on the homepage that should take hime to a user profile, say:

/user/{id}

Where will I decide how this URL looks like and which endpoint to call?

3

There are 3 best solutions below

0
Jerodev On

You can use the same route syntax, but instead of returning a view, you return a json response.

Route::get('api/user', function () {
    $data = ['status' => 'success', 'data' => 'stuff'];
    return response()->json($data);
});

Take a look at the response documentation for all available types of responses.

0
Seif On

I finally wrapped my head around this. At least I think so.

in web.php I have a set of Closures with the URLs that I want. These Closures return views with no data. Similar to this:

Route::get('/', function () {
    return view('welcome');
});

And then in the view I call the API endpoints as specified in api.php to render the data that I need in the view.

// List activities
Route::get('activities', 'ActivityController@index');
0
NAVEEN KUMAR On

Laravel 5.3 and above provides the seperate route file routes/api.php, where you can write all routes related to your api requests.

for controller just create a seperate folder in controller folder named as 'Api' and create api related controller in that.

and from there you can write function for corresponding routes. and return json as return response()->json(['data'=>$data]);

Or you can use https://github.com/nWidart/laravel-modules package to create a sepperate api module in laravel.