Reputation: 1047
I am building a web app + REST server with Laravel 5.5 so that the users can either access the services online with a web interface or indirectly use the APIs via the mobile app.
Now the objective would be to have the same controllers capable of handling both API and direct requests leveraging on Laravel built-in double routing and automatic JSON responses for FormRequests.
The main problems I am figuring are:
A possible approach to the second issue would be to use "findOrFail" and then catch the exception, looking whether the request has got an "Accpet" header and reply accordingly but it looks quite bulky.
Here is a brief overview of a controller I am working on; I haven't implemented any checks on the retrieved data yet.
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::all();
return UserResource::collection($users);
}
/**
* Store a newly created resource in storage.
*
* @param \Washery\Http\Request\StoreUser $request
* @return \Illuminate\Http\Response
*/
public function store(StoreUser $request)
{
User::create($request->all());
return response()->json(['message' => 'success'], 200);
}
/**
* Display the specified resource.
*
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
return new UserResource($user);
}
/**
* Update the specified resource in storage.
*
* @param \Washery\Http\Request\UpdateUser $request
* @return \Illuminate\Http\Response
*/
public function update(UpdateUser $request)
{
User::update($request->all());
return response()->json(['message' => 'success'], 200);
}
/**
* Remove the specified resource from storage.
*
* @param \Washery\User $user
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
User::find($id)->delete();
return response()->json(['message' => 'success'], 200);
}
}
Upvotes: 1
Views: 5557
Reputation: 13259
An approach would be to know where the request is coming from. If it comes from the mobile (API request), then return JSON, else, return a view.
if ($request->expectsJson()) {
return response()->json(['message' => 'success']); // No need to put 200 here.
} else {
return view('view.path');
}
You can learn more about the request api here: https://laravel.com/api/5.5/Illuminate/Http/Request.html
Upvotes: 3