简体   繁体   中英

Laravel: Combine REST-Controllers with normal controllers and views?

I want to create an new app and for this purpose I've chosen laravel. So I'm also new to laravel.

I want to integrate an API from the beginning for things like browser addons or mobile apps. Of course I don't want to make it an API only app. I'll still need normal views and controllers which will handle this. Now I'm a bit confused about the proper structure. It should output the data as JSON when it's an API request, otherwise as a normal view.

What would be the best way to achieve this? All tutorials are based on API only apps which doesn't help me.

Is it good practice to make UserController.php and ApiUserController.php? Or UserController.php and a subfolder structure like API/v1.0/UserController.php? Wouldn't I repeat things often with this kind of structure? I mean often the only thing changes is the output, isn't it?

Thanks in advance!

Your API should be served on API routes, those can be in the same controller as the other user stuff but they really don't have to be.

I like to use an ApiController with all the API functions in it. In that you can implement stuff like "showUsers" and have it return User::all() or User::paginate(50). If you directly return a Model in Laravel it will output as JSON by default, which is pretty convenient.

Now for some real API goodness, I love using the API package by dingo in combination with artdarek's Laravel OAuth 2 wrapper. It providers really high quality secure API with lots of functionality, like rate limiting and scopes and all that cool stuff.

You really don't want to use RESTful controllers for an API, since you probably want differently named endpoints. I like to keep all users at api/users but single users at user/USER for example. It's just what I prefer, my API should be totally customizable and routable in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM