How to change the subject of email in mailable class in laravel 6. The subject on email showing is 'Send Email'. email is sending properly. the only problem is I am not able to change the subject of the email.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendEmail extends Mailable
{
use Queueable, SerializesModels;
protected $user;
public function __construct($user)
{
$this->user = $user;
}
public function build()
{
return $this->view('mails.verify_account')->with([
'email_token' => $this->user->email_token,
]);
}
}
You may use subject method:
public function build()
{
return $this->subject('Your subject')
->view('mails.verify_account')
->with([
'email_token' => $this->user->email_token,
]);
}
Check Laravel docs for more info.
in your __construct, add: $this->subject('bla bla');
Related
I am getting a super strange error when I am creating a markdown email with Laravel.
I have a simple Markdown email (code below), the issue is with line 43 at "return new Content("
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Envelope;
use App\Models\User;
class RegisteredUser extends Mailable
{
use Queueable, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function content()
{
return new Content(
view: 'users.register.new',
with: [
'name' => $this->name,
],
);
}
public function build()
{
return $this->content();
// return $this->markdown('users.register.new');
}
}
The error I get is:
local.ERROR: Class "Illuminate\Mail\Mailables\Content" not found {"exception":"[object] (Error(code: 0): Class \"Illuminate\\Mail\\Mailables\\Content\" not found at www/app/Mail/RegisteredUser.php:43)
How is that possible? Shouldn't that be included with Laravel 9? (9.19)
How do I fix this?
Turns out the syntax I am using was introduced in Laravel 9.3 so I had to update Laravel using:
composer update.
PS. I was able to solve this from the help of Laravel's official discord group. Thank you <3
On a project I have I am using Fortify as my BE. I need a multilingual app, therefore I added the
'prefix' => {locale}' to config/fortify.php.
Login, registering, and 2FA, are working ok, but the problem arrives with the email verification process.
If I try to click on the link received by email, it goes to the /email/verify and returns a forbidden page error.
Then if I request to get another verification email it returns the error displayed on the title of the question.
Probably it has something to be with the locale parameter because when I run route::list, the verification.verify route is displayed with the endpoint of {locale}/email/verify/{id}/{hash}, so I assume that the link on the request another mail is causing the error since it is referenced as /email/verify/{id}/{hash}.
So does anyone know how to change it?
Or has anyone faced a similar problem regarding Fortify and these localization routes?
What I had to do was to customize some of the default Fortify functions, extending some classes in order to add the locale parameter to them.
When a new user is registered (event) it sends the verification email (listener), so I had to configure the files involved in this flow.
<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Registered;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
class SendEmailVerificationNotification implements ShouldQueue
{
use Queueable;
public function handle(Registered $event)
{
if ($event->user instanceof MustVerifyEmail && ! $event->user->hasVerifiedEmail()) {
$event->user->sendCustomVerificationEmailNotification();
}
}
}
And create the function sendCustomVerificationEmailNotification on the user's model and the notification CustomVerificationNotification that will be sent.
public function sendCustomVerificationEmailNotification()
{
$this->notify(new CustomVerificationNotification);
}
<?php
namespace App\Notifications;
use Carbon\Carbon;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;
class CustomVerificationNotification extends VerifyEmail
{
protected function verificationUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable);
}
return URL::temporarySignedRoute(
'verification.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'locale' => app()->getLocale(),
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
]
);
}
}
Then in case, the user wants an additional verification email notification, this is handled through a function on the EmailVerificationNotificationController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
class CustomEmailVerificationController extends EmailVerificationNotificationController
{
/**
* Send a new email verification notification.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->user()->hasVerifiedEmail()) {
return $request->wantsJson()
? new JsonResponse('', 204)
: redirect()->intended(Fortify::redirects('email-verification'));
}
$request->user()->sendEmail();
return $request->wantsJson()
? new JsonResponse('', 202)
: back()->with('status', 'verification-link-sent');
}
}
Using Database Notification I have stored notification in the notification table.
But now I want to display the notification in the blade template.
I have faced an undefined error.
Controller
$data=Employee::create([
'first_name'=>$request->input('first_name'),
'last_name'=>$request->input('last_name'),
'username'=>$request->input('username'),
'email'=>$request->input('email'),
'password'=>$request->input('password'),
'confirm_password'=>$request->input('confirm_password'),
]);
$admin=Employee::find(1);
$admin->notify(new NotifyAdmin($data));
NotifyAdmin class
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
use App\Models\Employee;
class NotifyAdmin extends Notification implements ShouldQueue
{
use Queueable, Notifiable;
private $val;
public function __construct(Employee $employee)
{
$this->val=$employee;
}
public function via($notifiable)
{
return ['database'];
}
public function toArray($notifiable)
{
return [
'username'=> $this->val->username
];
}
}
After doing this, the notification is stored in the notification table.
Now I want to display this notification
<div class="media-body">
#foreach($employee->notifications as $row)
<p class="noti-details"><span class="noti-title">Admin</span> added new doctor <span class="noti-title">{{$row->data['username']}}</span></p>
<p class="noti-time"><span class="notification-time">4 mins ago</span></p>
#endforeach
</div>
this is my controller
<?php
namespace App\Http\Controllers;
use App\Models\Employee;
use Illuminate\Http\Request;
use App\helpers\helper;
use App\Notifications\NotifyAdmin;
class EmployeeController extends Controller
{
public function InsertEmployees(Request $request)
{
$data=Employee::create([
'first_name'=>$request->input('first_name'),
'last_name'=>$request->input('last_name'),
'username'=>$request->input('username'),
'email'=>$request->input('email'),
'password'=>$request->input('password'),
'confirm_password'=>$request->input('confirm_password'),
'phone'=>$request->input('phone'),
'nid_number'=>$request->input('nid_number'),
'status'=>$request->input('status'),
'roles'=>$request->input('roles'),
'join_date'=>$request->input('join_date'),
]);
$admin=Employee::find(1);
$admin->notify(new NotifyAdmin($data));
I am trying to use Laravel Notification to send email but getting this error
{
"message": "Type error: Argument 1 passed to App\\Notifications\\UserResetPasswordNotify::__construct() must be an instance of App\\Notifications\\User, instance of Illuminate\\Database\\Eloquent\\Collection given, called in /home/fy3bgmgte060/public_html/svs.com/app/Http/Controllers/Api/LoginController.php on line 143",
"status_code": 500
}
My Controller function
public function resendOTPTest(Request $request)
{
$user = User::where(['mobile' => $request->mobile])->first();
Notification::send($user, new UserResetPasswordNotify($user));
return response()->json(['message' => 'success','data' => 'OTP Sent', 'success' => true], 200);
}
my Notification file
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class UserResetPasswordNotify extends Notification
{
use Queueable;
public $user;
public function __construct(User $user)
{
$this->user = $user;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
$user = $this->user;
return (new MailMessage)
->from('info#test.com')
// ->name('Entrance India')
->subject('New OTP from SVS ')
->markdown('mail.userResetPassword', compact('user'));
}
public function toArray($notifiable)
{
return [
//
];
}
}
this id my User Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Order;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'fname','lname', 'email','gender', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
}
while trying to use Laravel Notification to send email but getting above error
But same thing is working for User creation function but it is not working for reset Password function
Where am I wrong?
Include User Class in your Notification Class
You are Injecting User Dependency as Typehint to the Magic Method __Cunstructor into your Notification Class.
You have to make sure Class is available there.
Simply use this in your Notification Class.
use App\User
You need to add
use App\User
in Notification file.
Try using $user->notify(new UserResetPasswordNotify($user))
I try on the my localhost, it works
But if I try on the staging server, it does not works
My controller like this :
<?php
use Illuminate\Support\Facades\Mail;
use App\Mail\OrderReceivedMail;
...
class PurchaseController
{
...
public function test() {
$order = $this->order_repository->find(416);
$user = $this->user_repository->find(1);
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
}
}
My mail like this :
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class OrderReceivedMail extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
public $order;
public $store;
public function __construct($order, $store)
{
$this->order = $order;
$this->store = $store;
$this->subject('subject');
}
public function build()
{
$mail_company = explode(',',config('app.mail_company'));
// dd($mail_company, $this->order->number, $this->store->name, 'test');
return $this->view('vendor.notifications.mail.email-order',['number'=>$this->order->number, 'store_name' => $this->store->name])->bcc($mail_company);
}
}
I try add this :
dd($mail_company, $this->order->number, $this->store->name, 'test');
on the mail
If in my localhost, the result of dd show
But if in the staging server, the result of dd not show
Seems if the staging server, it does not run this statement :
Mail::to($user)->send(new OrderReceivedMail($order, $order->store));
How can I solve this problem?
open config/mail.php, .env files and set your email driver as mail as bellow,
'driver' => env('MAIL_DRIVER', 'mail'), //you must set it in env file too
then you can send emails like bellow, note that emails.admin.member, is the path to your email template, in the example code, laravel will look for a blade template in the path, resources\views\emails\admin\member.blade.php
Mail::queue('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});
or
Mail::send('emails.admin.member', $data, function($message) {
$message->subject("A new Member has been Registered" );
$message->from('noreply#mydomain.net', 'Your application title');
$message->to('yourcustomer#yourdomain.com');
});