Laravel 5.5 - Mailgun catch email errors - laravel

I am sending email via Mailgun from a Laravel 5.5 app like this...
Mail::send('emails.sendmessage', $data, function($message) use ($data) {
$message->to($data['email']);
$message->from('me#example.com.com', 'Ueer');
$message->subject('Sample Email');
});
/* Return Success Response */
return Response::json(array(
'error' => false,
'status_code' => 200,
'response' => 'success',
));
How can I catch Mailgun errors with this code? Sometimes MailGun returns an error message and I would like to return a different response if this happens

You can take a look at this question : Laravel 5 - How Do You Catch an Mail::send() Error?
Adding a try and catch should do the trick.
If you don't want to add a try/catch for whatever reason, I would recommend you to validate beforehand every parameters susceptile of throwing an error from Mail::send

Related

How To Get Relevant Error Data Message From Failed Validation And Failed Guzzle Call In Laravel

I have an api call being made in Laravel using Guzzle/Http. When an error happens I catch it in a try/catch block. I then get the message, but the problem is, I don't want this ugly message that comes back but rather the actual nested message within the $e exception variable. The problem is that the getMessage() method returns a long string from Guzzle.
Error String from $e->getMessage().
"""
Client error: `POST http://mywebApp.com/api/users` resulted in a `422 Unprocessable Entity` response: \n
{"message":"The given data was invalid.","errors":{"email":["This email is not unique"]}}]\n
"""
All I want from this string is:
This email is not unique
The API call
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;
try {
$client->request('POST', 'http://mywebApp.com/users', [
'name' => 'John Doe',
'email' => 'nonuniqueemail#test.com',
]);
} catch (RequestException $e) {
$test = $e->getMessage();
dd($test) //The long message from above
}
If you look closely, the response body is actually a json and can be converted into an array containing the message and an array of errors. You can call json_decode($data, true) and you should get an associative array of the response. In your case something like this should work.
$response = $client->request('POST', 'http://mywebApp.com/users', [
'name' => 'John Doe',
'email' => 'nonuniqueemail#test.com',
]);
$bodyData = $response->getBody();
$errors = json_decode($bodyData, true)['errors'];

Where to fill message of auth.failed in invalid login?

In Laravel 8 app with fortify on invalid login I get error
auth.failed
in email error block.
I checked and added line in resources/lang/en/auth.php, but it did not help.
Where have I to add error message?
Thanks!
The LoginController only uses the 2 messages found in the translation file resources/lang/en/auth.php
'failed' => 'These credentials do not match our records.',
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
So you'd need to change it there.
If you look at the AuthController, you'll see it uses the AuthenticatesUsers trait. If you look in that trait, you'll see
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
which is where it's loading the auth.failed message from.

Route::get returns blank in Laravel 8 API

I have installed the newest version of laravel which is Laravel 8. Now, I'm making an API and encountered this weird problem. I'm doing the API wayback Laravel 5.6 so it's not new to me.
Problem:
Route::apiResource('/test', UserController::class);
The GET method returns blank when using postman even when I wrapped it in auth:api middleware to check if {"message":"Unauthenticated."} will be shown but it does not. Meaning, even error is not working. But when I changed my route to post, it worked.
Here's my route list:
Here's the POSTMAN response for GET method:
Here's the POSTMAN response for POST method:
Here's the controller:
public function index()
{
return response()->json([
'success' => true,
'data' => ['test' => 'test'],
'message' => 'Success'
], 200);
}
public function store(Request $request)
{
return response()->json([
'success' => true,
'data' => ['test' => 'test'],
'message' => 'Success'
], 200);
}
As you can see they are the same so the postman should returns the same for GET and POST. I already tried route:clear but it doesn't work.
Thank you.
The GET request on api/test is captured by the GET route {vue}

Laravel api Authenticate - 500 error in login

i have laravel api in my site , it work fine in localhost but when deploy on heroku , it work good for Signup and signupActivate but for Login i get error 500
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
$credentials['active'] = 1;
$credentials['deleted_at'] = null;
if(!Auth::attempt($credentials))
return response()->json([
'message' => __('auth.login_failed')
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
// return $token;
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
]);
}
{
"message": "Server Error"
}
500 Internal Server Error
A generic error message, given when no more specific message is suitable.
What can I do to solve this problem ?
I'm sorry that I could not answer before, but I hope this can be helpful for someone with a similar problem.
When you have an error and do not find the problem, try to see the log that is in logs/laravel.log
I had an auth error and the only thing that I could do was get a message that contained 500 internal server error.
When I read the log, I found an error in the database credentials, because I was editing the .env file on master branch with the production credentials, but when I was trying to add another feature, this data was saved in cache, when I erased the cache, the error was solved.
Remember, the logs/laravel.log is your best friend when you want to debug.
Try adding try..catch.. to your code and check the exact error message your are getting.
try{
// your code here.
}catch(Exception $e){
dd($e);
}
Hope this helps :)

Error from Laravel to AJAX fileupload

I have an AJAX upload that sends the uploaded file (image in this case) to a function in Laravel 5.3. There I have this validation check in said function:
...
$validator = Validator::make($request->all(), [
'image' => 'image|mimes:jpeg,png,jpg|max:512',
]);
// If validator fails return this error to AJAX
if($validator->fails()) {
return response()->json('error', 422);
}
...
How would I be able to set the response()->json('error', 422) with a custom error. Now I only get an error that the file upload has failed. I would like more feedback then that.
For example: let the user know his file is to large or let the user know his extension is not allowed.
Thanks
You can get error messages from validator and send it to response, here is example.
if ($validator->fails()) {
return response()->json([
'success' => false,
'error' => $validator->getMessageBag()->toArray()
], 422);
}

Resources