Reputation: 61
I'm developing and College project, It should be a platform that serve and Web and Mobile Front-En. I decided to use Laravel 5.1, my idea was to use laravel as an excelent hardcore php backend to serve this platform, I wanted to develope APIsRest with laravel and comsume the services on both web and mobile front-end. My point is: I don't wanna use blade templating engine, because returning "views, instance objects, etc" my mobile front won't understand responses, that's why I want to orientated my APIs to return JSONs messanges, so I can handle them on each front.
1) First at all I wanna ask you guys if is it a good idea? 2) how can I retrieve the error php messages send by laravel to send them back to views (mobile-web front) as JSONs?
Example: Right now I'm trying to finish the "Login-Register" module of my project. I'm trying to use the advantages of Authentication Laravel Module, and now I am stack on postLogin, because i don't know how to handle the error and send it back to front as JSON.
public function postIngresar(Request $request)
{
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return response()->json(*$this->sendLockoutResponse($request));
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return response()->json([
'success' => 'true',
'message' => 'Logeo logrado exitosamente'
]);
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return response()->json($this->getFailedLoginMessage());
}
is there any way to handle all error and exception as JSON messages? It'll will help me A LOT.
thank you so much by reading.
Upvotes: 0
Views: 1921
Reputation: 7489
The LoginController
uses the AuthenticatesUsers
trait which has a method sendFailedLoginResponse
which is responsible for the error message redirect upon authentication failure as follows:
protected function sendFailedLoginResponse(Request $request)
{
if ( ! User::where('email', $request->email)->first() ) {
return response()->json([
$this->username() => Lang::get('auth.email')
]);
}
if ( ! User::where('email', $request->email)->where('password', bcrypt($request->password))->first() ) {
return response()->json([
'password' => Lang::get('auth.email')
]);
}
}
Upvotes: 1
Reputation: 3543
You can read about Exception Handling
section of the Laravel docs, but to save you the time, here is the name of the method that will be responsible for returning json representation of your errors:
All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response
Upvotes: 1