Slack Laravel Formatting - laravel

So notifications work no problems, on my user model i am routing to slack as such:
/**
* Route notifications for the Slack channel.
*
* #return string
*/
public function routeNotificationForSlack()
{
return env('SLACK_WEBHOOK_URL');
}
However when it comes time to make changes, the following from and to methods have no effect.
return (new SlackMessage)
->from('Ghost', ':ghost:')
->to('#channel-name')
What do i need to do to post to another channel? and change the from would be nice!

Related

Laravel 8 Mail Notifications

I'm using Laravel 8, and my Client asks to be able to modify the mailables content.
I need to show the different notification templates, and let the users add text, action buttons, etc.
I'm thinking on building a DB structure to store the different fields with the corresponding order, but I'm not sure if it is possible to apply that on the toMail method.
For example: a NotificationTemplate Model that hasMany NotificationField (this can have type and content).
And then try to use it as a query builder:
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$fields = NotificationTemplate::where('name', 'example')->fields;
$mail = (new MailMessage);
foreach($fields as $field){
if($field->$type = 'line'){
$mail->line($field->content);
}
}
return $mail;
}
Is this possible? Or is there another way to allow the admins of a Laravel 8 app to modify the Mail notificiation message from the frontend?
Thanks, HernĂ¡n.
You can simply give the admin a textarea where he can customize the content of email.
I use this package armincms/option to stock the content and in your template email you can use option()->content

Send SMS from laravel?

I have created a notification class called Test. When I called this class from here $user->notify(new Test($user,$password,$message)); which method is called?.
I want to send SMS but inside that, it has a predefined method called
public function toMail($notifiable)
{
return (new MailMessage)
->line('The introduction to the notification.')
->action('Notification Action', url('/'))
->line('Thank you for using our application!');
}
should I create another function for sending SMS? and how can I do that?
because I want to send an SMS to a URL something like this
$url='URL.php?USER=aaaa&PWD=bbbb&MASK=cccc&NUM='07453727272''&MSG='This is a message';
Inside your class there is a via method which is an array, returning, in your case. Mail. You may want to change that to 'nexmo' for example.
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['nexmo'];
}
The via method receives a $notifiable instance, which will be an
instance of the class to which the notification is being sent. You may
use $notifiable to determine which channels the notification should be
delivered on:
Depending on the Gateway you are using for SMS there may be a specific notification which applies already: (see left hand navigation)
https://laravel-notification-channels.com/clickatell/
If you need a custom one, you should be able to follow the examples of some of the notifications channels already built to create your own. I'd add the specific SMS gateway you are using for clarity to see if I can provide additional information.

Add extra question to Laravel forgotten password form and custom its error messages

I'd like to customize the forgotten password form in Laravel.
When asking to reset the password, the user will have to answer a simple question (the name your first pet, the name of your childhood best friend, etc) besides inserting his/her email. This is to avoid other people asking password reset if they know the account's email, but are not the owner of the account.
I also would like to custom the errors messages to, actually, not show errors. For example, if an invalid email is inserted, it would not show the error message "We can't find a user with that e-mail address." I don't like it because someone may guess the email of a user by trying different emails until she/he stops getting the error message. Instead, I would like to show the message "If the information provided is correct, you will receive an email with the link to reset your password."
How to add these functionalities to Laravel auth?
I am looking for a solution that I don't have to create an entire login system from scratch (I think that if I try to design everything from scratch I'd probably miss something and create security vulnerabilities). I'd like to keep the Laravel auth system and just add these two features.
Feel free to suggest other ways to achieve the desired result and to make my question clearer. I'll appreciate that.
The good news is you don't need to rewrite everything.
The bad news is, you need to understand traits and how to extend/override them, which can be a little confusing.
The default controller that Laravel creates ForgotPasswordController doesn't do much. Everything it does is in the trait. The trait SendsPasswordResetEmails contains a few methods, most importantly for the validation in validateEmail method.
You can override this validateEmail method with one that checks for an answered question. You override traits by altering the 'use' statement.
For example change;
use SendsPasswordResetEmails
to:
use SendsPasswordResetEmails {
validateEmail as originValidateEmail
}
This will tell the code to re-name the original method validateEmail to originValidateEmail allowing you to create a new validateEmail in your own ForgotPasswordController.
You can then, inside ForgotPasswordController add a replacement which will be called by the default reset password code:
protected function validateEmail(Request $request)
{
// add in your own validation rules, etc.
$request->validate(['email' => 'required|email', 'questionfield' => 'required']);
}
To alter the error message, you can simply edit the language file found in resources/lang/en/passwords.php
Hope that helps.
Thanks to the user #Darryl E. Clarke, I managed to solve the problem. Here is what I did:
Add this line at the top of the file ForgotPasswordController, after namespace:
use App\User;
Add these 3 methods in the same file:
/**
* Send a reset link to the given user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
public function sendResetLinkEmail(Request $request)
{
$this->validateRequest($request);
// We will send the password reset link to this user. Regardless if that
// worked, we will send the same response. We won't display error messages
// That is because we do not want people guessing the users' email. If we
// send an error message telling that the email is wrong, then a malicious
// person may guess a user' email by trying until he/she stops getting that
// error message.
$user = User::whereEmail($request->email)->first();
if ($user == null) {
return $this->sendResponse();
}
if ($user->secrete_question != $request->secrete_question) {
return $this->sendResponse();
}
$this->broker()->sendResetLink(
$this->credentials($request)
);
return $this->sendResponse();
}
/**
* Validate the given request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateRequest(Request $request)
{
$request->validate(['email' => 'required|email', 'secrete_question' => 'required|string']);
}
/**
* Get the response for a password reset link.
*
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
*/
protected function sendResponse()
{
$response = 'If the information provided is correct, you will receive an email with a link to reset your password.';
return back()->with('status', $response);
}
Customize it the way you want.
Hope that it will helps others!!

how to intercept graphql request in api-platform?

i'm using api-platform 2.3.5 and i can't find a way to intercept a graphQl request.
I mean that let's say i'm making a mutation (update) and want to also log the data or send an email. How do i do that ?
I did read the api-platform documentation, but there's very little about their implementation of graphQl. It does quite a lot automagically.
Events are not yet implemented (https://github.com/api-platform/core/pull/2329)
I also found this - https://github.com/api-platform/core/blob/master/src/GraphQl/Resolver/Factory/ItemMutationResolverFactory.php#L101
but i'd rather not touch it. Is there a simpler way ?
I know this is a bit old but if only for reference.
The recommended way with API-Platform's graphql is to use stage. See this documentation.
In the case of the sending an e-mail you can use the serialize stage. See example below for sending email to notify user he has received a message.
<?php
namespace App\Stage;
use ApiPlatform\Core\GraphQl\Resolver\Stage\SerializeStageInterface;
use App\Email\Mailer;
final class SerializeStage implements SerializeStageInterface
{
/**
* #var Mailer
*/
private $mailer;
private $serializeStage;
public function __construct(
SerializeStageInterface $serializeStage,
Mailer $mailer)
{
$this->serializeStage = $serializeStage;
$this->mailer = $mailer;
}
/**
* #param object|iterable|null $itemOrCollection
*/
public function __invoke($itemOrCollection, string $resourceClass, string $operationName, array $context): ?array
{
// Call the decorated serialized stage (this syntax calls the __invoke method).
$serializedObject = ($this->serializeStage)($itemOrCollection, $resourceClass, $operationName, $context);
// send notification e-mail if creating message
if ($resourceClass === 'App\Entity\Message' && $operationName === 'create') {
$this->mailer->sendMessageNotificationEmail($itemOrCollection->getReceiver());
}
return $serializedObject;
}
}
Then we need to decorate the native stage:
/config/services.yaml
App\Stage\SerializeStage:
decorates: api_platform.graphql.resolver.stage.serialize

Slow down Laravel worker

I have hooked up Redis with Laravel for queuing emails and all is fine...
but in dev environment I use mailtrap.io (free version).
And the problem is that mailtrap allows to receive only 2 emails per second, so I never get all the emails that are queued, because redis sends emails like crazy... maybe 10 per/s
Is there a way somehow to slow down the queue so that it sends max 2 mails per second?
Yes It is a solution and they're called jobs :)
you can create a file to send emails exclusively in the Jobs Folder and a class like this
class SendPushNotification extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $pushNotification;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(PushNotification $pushNotification)
{
$this->pushNotification = $pushNotification;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
$this->pushNotification->send();
}
}
And then call the class in the controller
$this->dispatch(new SendPushNotification($pushNotification))->delay(1);
Delay is for seconds you can create a constructor with an array to receive two emails o many you want maybe some var than can be changed by the .env to change the number of emails per second

Resources