Change FROM and REPLYTO address in Laravel 5.4 - laravel

i can't send email with user address as FROM and Reply To
In the FormRequest :
public function persist()
{
$reservation = Resa::create(
$this->only(['nom', 'email', 'phone', 'formule', 'date_arr', 'date_ret', 'nb_adu', 'nb_enf', 'lemessage'])
);
Mail::to('contact#cotiga.fr')
->from($reservation->email, $reservation->nom)
->replyTo($reservation->email, $reservation->nom)
->send(new Reservation($reservation));
}
I have the error :
FatalThrowableError in ReservationForm.php line 48:
Call to undefined method Illuminate\Mail\PendingMail::from()
I tried full of possibility, but I can not change the field FROM and REPLYTO
Can you help me ?
Thank's

The Mail Facade does not implement the replyTo() method anymore. Instead this method has moved to the Mailable class itself. Official documentation proposes to use the build() method to setup the Mailable, however this is not always convenient (eg the replyTo field might be different each time)
However if you still want to use a similar syntax you can use:
$mailable = new myMailableClass;
$mailable->replyTo('reply#to.com');
Mail::to('email#tocom')
->send($mailable);
For a complete list of available methods on the Mailable class see the Mailable Documentation

In Laravel 5.4 Mailables, the replyTo, subject, cc, bcc and others can be set inside the mailable in the build method. This is also true for the to which can also be set on the Mail facade.
Here is a simple example of a contact form mailable using an array of attributes:
You may use the to static method directly on the Mail facade, but as an example, we're going to set it inside the mailable:
Mail::send(new ContactCompany($attributes));
Then set the replyTo inside the build method:
class ContactCompany extends Mailable
{
use Queueable, SerializesModels;
public $attributes;
/**
* Create a new message instance.
*
* #param $attributes
*/
public function __construct($attributes)
{
$this->attributes = $attributes;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$this->to($this->attributes['departmentEmail'], config('app.name'));
$this->replyTo($this->attributes['email'], $this->attributes['name']);
$this->subject(sprintf("New contact message from %s", $this->attributes['name']));
return $this->markdown('emails.contact.company');
}
}
Please, note that Mail::alwaysFrom() and Mail::alwaysReplyTo() can be used before Mail::send() to set the from and replyTo of all emails, so make sure to use them with care.

The preferred method of sending emails are now mailables and you can set from and reply to using from() or replyTo() methods.
However using plain Mail facades you should try to use alwaysFrom and alwaysReplyTo methods. However after sending such e-mail you should set again previous values to be sure no other emails will be impacted by this change.
But looking at method names it might be not the best solution so better is to look at mailables and use them to send e-mails in latest Laravel releases.

Problem resolved.
I edit app>Mail>Reservation.php
public function build()
{
// return $this->markdown('emails.reservation-email');
return $this->from($this->reservation->email)->markdown('emails.reservation-email');
}
app>Http>Request>ReservationForm.php
public function persist()
{
$reservation = Resa::create(
$this->only(['nom', 'email', 'phone', 'formule', 'date_arr', 'date_ret', 'nb_adu', 'nb_enf', 'lemessage'])
);
Mail::to('contact#cotiga.fr')->send(new Reservation($reservation));
}

Related

Telegram notifications in Octobercms plugin

I would like to send a telegram message to a specific user at 17:00 using laravel's Telegram notification channel, I however can't seem to get it going. I currently use a cmd command for testing, but keep getting errors and don't know what to do.
Here are my files for the command and notification:
SendNotification.php
<?php
namespace Rogier\Lab\Console;
use Illuminate\Console\Command;
use Rogier\Lab\Notifications\DailyTelegram;
class SendNotifications extends Command
{
protected $name = 'lab:notifications:send';
protected $description = 'Send notifications';
protected $userid = 919871501;
/**
* Execute the console command.
* #return void
*/
public function handle()
{
$this->output->writeln('Sending notifications');
$notification = new DailyTelegram($this->userid);
$notification->via()->toTelegram();
$this->output->writeln('Done');
}
}
and DailyTelegram.php
<?php
namespace Rogier\Lab\Notifications;
use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
class DailyTelegram extends Notification
{
protected $userid = 919871501;
public function via()
{
return [TelegramChannel::class];
}
public function toTelegram()
{
return TelegramMessage::create()
// Optional recipient user id.
->to($this->userid)
// Markdown supported.
->content("Hello there!\nYour invoice has been *PAID*");
}
}
I currently get the error "Call to a member function toTelegram() on array", but I feel like I tried everything, maybe I'm doing it completely wrong. Does anyone know how I should do it?
thanks in advance
Yes, you are doing it wrong. Notifiables have notify() method, you should use it:
$user->notify(new DailyTelegram);
In this example $user is App\User instance (which is notifiable out of the box).
You should check out both Laravel's sending notifications and laravel-notification-channels/telegram docs.

Changing the default “Subject” field for verification emails in Laravel 5.7

I'm trying to change the default subject field in the verification email that comes with Laravel 5.7. How and where do I change it? I have searched all over the place and online. Because it's brand new I can't find an answer.
You don't need to code anything. The notification has all the strings wrapped in the Lang class so that you can provide translation strings from english to another language, or even english to english if you just want to change the wording.
Look in /vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable);
}
return (new MailMessage)
->subject(Lang::getFromJson('Verify Email Address'))
->line(Lang::getFromJson('Please click the button below to verify your email address.'))
->action(
Lang::getFromJson('Verify Email Address'),
$this->verificationUrl($notifiable)
)
->line(Lang::getFromJson('If you did not create an account, no further action is required.'));
}
You can see all the strings there.
Create a file en.json if you don't have one on the resources/lang folder already.
add the original string and the replacement.
eg
{
"Verify Email Address": "My preferred subject",
"Please click the button below to verify your email address.":"Another translation"
}
To translate to another language, change the locale in config/app.php and create a translation file with the locale.json
This is the MustVerifyEmail trait
<?php
namespace Illuminate\Auth;
trait MustVerifyEmail
{
/**
* Determine if the user has verified their email address.
*
* #return bool
*/
public function hasVerifiedEmail()
{
return ! is_null($this->email_verified_at);
}
/**
* Mark the given user's email as verified.
*
* #return bool
*/
public function markEmailAsVerified()
{
return $this->forceFill([
'email_verified_at' => $this->freshTimestamp(),
])->save();
}
/**
* Send the email verification notification.
*
* #return void
*/
public function sendEmailVerificationNotification()
{
$this->notify(new Notifications\VerifyEmail);
}
}
As you can see is sending a Notification named VerifyEmail, so i think overriding this method on the user model with your own notification would be enough. You should also check this file: vendor/laravel/framework/src/Illuminate/Auth/Notifications/VerifyEmail.php since it contains the notification and can be used as an example to your custom verify notification.
In User.php
public function sendEmailVerificationNotification()
{
$this->notify(new MyNotification);
}
Then run
php artisan make:notification MyNotification
And in your notification you can just extend to Illuminate\Auth\Notifications\VerifyEmail
Then you can override the notification toMail function... Haven't given it a try, but that should work.
Can you post your function where you mail?
I use:
\Mail::to($user)->subject('Your Subject')->bcc([$reports,$me])->send(new Declined($user));
Which is: send a mail to the $user, set the subject, blind copy in, then send the mail whilst passing in the user. This is for markdown mail also. You use the -> operator to add all of the extras for the mail, so with that you can add in BCC (like I have done) and also CC etc.

Laravel 5 - sanitize certain inputs on validation

Is it possible to sanitize certain inputs on (or before validation)?
I have this rules for now (as example):
public function rules()
{
return [
'name' => 'required|min:3|max:255|string',
'description' => 'string',
'hours.*' => ['required', new Hours],
];
}
I want to sanitize name and description, but I don't to sanitize hours. Is this possible to do on validation, or I have to sanitize after validation and before insert?
I don't recommend to do sanitization after validation.
Suppose we have a blog system and guests/users can comment on posts, and the minimum characters in a comment is 10
If someone comments with thank you (there's a trailing space), it will be passed at the validation level because it's a 10 chars comment, but when we sanitize the comment, say we trim it, it will be left with 9 chars. This is a silly example but can be something very important in your business logic somewhere.
Sanitize then validate.
To do request inputs sanitization, this article has a good pattern to do it https://medium.com/#melihovv/how-to-sanitize-input-data-in-declarative-manner-in-laravel-e4486068f751
To cannot do this before validation as the original value will still be there in request. It can be easily dealt with mutators.
You can use Eloquent's Mutators to format attribute values in Eloquent Model before insert or update.
To define mutator, add set prefix and attribute suffix with the attribute's name. Like following
// Name mutator
public function setNameAttribute($name)
{
$this->attributes['name'] = strtolower($name); // used strtolower just to show the mutation
}
// Description mutator
public function setDescriptinAttribute($description)
{
$this->attributes['description'] = strtolower($description); // used strtolower just to show the mutation
}
Check documentation for more info https://laravel.com/docs/5.6/eloquent-mutators#defining-a-mutator
The only way I could think of validating the input like that would be validating it on the client side. So basically using Javascript to validate it. If the user for some reason disables Javascript your server site validation would work. What you could try as well would be to post the data asynchronous using Ajax for instance and immidietly return an error message if the validation fails, this approach would be server side.
test this :
web.php
Route::get('test/', 'TestController#test');
TestController class :
<?php
namespace App\Http\Controllers;
use App\Http\Requests\PostRequest;
use App\Post;
class PostController extends Controller
{
public function test(PostRequest $request)
{
dd($request->get('name'));
}
}
PostRequest class :
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class PostRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$this->sanitize();
return [
'name'=>'required',
'description'=>'required',
'description'=>'required',
];
}
public function sanitize()
{
$input = $this->all();
$input['name'] = $input['name'].'some change';
$input['description'] = $input['description'].'another change';
$this->replace($input);
}
}
As you can see, I defined a method called sanitize in PostRequest
Now when I set the value of the name to the ‍‍ali in URL, but the ali some change value will be printed.
You can also use the daylerees / sanitizer package.

Override sendSwiftMessage() Laravel Swiftmailer with custom

I am using Laravel 4.2
The answer given by user3158900 is for Laravel 5.*
Any one can help me with version 4.2 ?
I would like to override sendSwiftMessage() protected function with my own function.
sendSwiftMessage() is located in
"vendor/laravel/framework/src/Illuminate/Mail/Mailer.php"
I created a
Lib/Mailer/CustomMailer.php
and Set the folder Lib to autoload in composer (PSR4).
I can now call/load my function in my controllers by writing:
new Lib\Mailer\CustomMailer;
This is how my file looks like:
<?php namespace Lib\Mailer;
class CustomMailer extends \Illuminate\Mail\Mailer {
/**
* Send a Swift Message instance.
*
* #param \Swift_Message $message
* #return void
*/
protected function sendSwiftMessage($message)
{
if (strpos($message->toString(), 'noemail#noemail.com') == true) {
Log::info('Not sending mail to noemail#noemail.com');
}
else
{
if ($this->events)
{
$this->events->fire('mailer.sending', array($message));
}
if ( ! $this->pretending)
{
$this->swift->send($message, $this->failedRecipients);
}
elseif (isset($this->logger))
{
$this->logMessage($message);
}
}
}
}
However, this sendSwiftMessage() function is not used when I send an email with Swiftmailer in my controller by doing EXAMPLE:
Mail::send(xxxx);
My question: How can I make Swiftmailer/Laravel use my custom sendSwiftMessage() function when I send a message if I don't want to modify all my Controllers that currently use the Mail::send() code
Think I got this figured out, however I am getting an error but I think that's on you because your custom class is using a property that doesn't exist so here's the solution anyway.
In AppServiceProvider.php in the boot() method, I've added the following:
$this->app->singleton('customMailer', function($app) {
return new CustomMailer(
$app['view'], $app['swift.mailer'], $app['events']
);
});
In app/Lib/Mailer folder, I've added another class for the facade.
namespace App\Lib\Mailer;
use Illuminate\Support\Facades\Facade;
class Mail extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'customMailer';
}
}
In config/app.php, I've replaced the Mail alias with the following...
'Mail' => App\Lib\Mailer\Mail::class,
And that should be all you need to do.
One other thing, I just noticed you are missing in your namespace the App which explains why you had to add the Lib folder to the autoloader. If you namespace it correctly to keep it inline with PSR-4 by adding the App\ onto the beginning, then you don't need to add anything to your composer.json file to get additional classes loaded.

How do I translate the subject of my password reset email in laravel 5

I am new to laravel and I am currently building a multilingual app. I am implementing password reset using laravels shipped methods. After looking at this method in ResetsPasswords trait:
protected function getEmailSubject()
{
return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}
I noticed that I can specify a variable for my subject in the PasswordController like so:
protected $subject = 'Password Reset';
How do I get this value from a language file and assign to the variable?
Use the trans() helper function in the contructor
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
class PasswordController extends Controller
{
use ResetsPasswords;
/**
* Create a new password controller instance.
*
* #return void
*/
public function __construct()
{
$this->subject = trans('passwords.subject');
$this->middleware($this->guestMiddleware());
}
}
After doing some digging I found the answer as shown below.
protected function getEmailSubject(){
return Lang::has('passwords.password_reset')
? Lang::get('passwords.password_reset')
: 'Your Password Reset Link.';
}
Using method overriding, I overrode the getEmailSubject method in the ResetsPasswords trait and provided the necessary implementation as shown in the body of the email. passwords.password_reset is a key for a text in my language file.

Resources