Send email when user registering in Laravel - laravel

I would like to send an email to a user that kinda says "Account created successfully" when user registration is done. I use tailwindcss ui. Below you can see pictures of controllers. I think I should write the code in the RegisterController. So, when someone registers, the system will automatically send mail to the new user.
Controllers
RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
What should I do here?

you can send an email by using the Mail facade with the ::send method. Here follows an example:
$to = 'receiver_name';
$email = 'receiver_address';
$mail_data = array(
//here you can pass data to the email blade view
);
Mail::send('viewname', $mail_data, function ($message) use ($to, $email) {
$message->to($email, $to)->subject('subject text');
$message->from('Sender name');
});

you can send a mail using notification. notify the user when he/she registers to the system. in your RegisterController
use App\Notifications\WelcomeEmail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->notify(new WelcomeEmail($user));
return $user;
}
now make the notification class with the artisan command
php artisan make:notification WelcomeEmail
and content for your notification class is
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class WelcomeEmail extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->view(
'welcome_email', ['user' => $this->user]
)
->from('support#yourcompany.com', 'Your Company Name')
->subject('Welcome Aboard');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
and finally make a blade file in the views folder welcome_email.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head
<body>
<h1>Hello {{ $user->name }}, Account created successfully</h1>
</body>
</html>
if you don't want to use notification, you can use the Mail facade to send a mail.
use Illuminate\Support\Facades\Mail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Mail::send('welcome_email', compact('user'), function ($message) use ($user) {
$message->to($user->email, $user->name)->subject('Welcome Aboard');
$message->from('support#yourcompany.com', 'Your Company Name');
});
return $user;
}
if you have set MAIL_FROM_ADDRESS in your env file you can skip the from part in the mail send function.

Related

How do I fix the Laravel page not found error?

After registering, it redirects to / home. But I get a 404 error. When I set the route to / home, I get 302 continuous routing errors.
RegisterController.php
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest');
}
Route.php
Auth::routes(['verify' => true]);
Route::get('/', 'HomeController#index')->name('home');
HomeController
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
if you have in your HomeController's construct a middleware that requires the user to be logged in then what you are getting is normal.
You should have a login page wich use the "guest" middleware.
or
login the user automatically once he registers before redirecting him to your home route.
Auth::login($user)
//or
Auth::loginUsingId($userId);
Remove guest middleware.
public function __construct()
{
$this->middleware('guest');
}
Your HomeController should look like
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
your route.php Look like
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
RegisterController should look like
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
make sure you're following laravel authentication.

Laravel: SMS not sending after Auth Registration using TextLocal transactional account

I am trying to send SMS OTP message using following code but the message is not being send. Below i have added my complete code. I am trying to send Message and email at same time message have send to register user but Otp SMS are not send. My TextLocal Account is transactional and i also have created SMS Template with that Template i am trying to send message .
My TextLocal Otp Template:
Use %%|OTP^{"inputtype" : "text", "maxlength" : "8"}%% as your login OTP.
OTP is confidential, Delish2go never call you for asking OTP. It valid for next 10 mins. Do not disclose OTP to anyone.
Notification page Code
Notifications/verifyEmailNotification.php
<?php
namespace App\Notifications;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use NotificationChannels\Textlocal\TextlocalChannel;
use NotificationChannels\Textlocal\TextlocalMessage;
class verifyEmailNotification extends Notification
{
use Queueable;
public $user;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail', TextlocalChannel::class];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('Please Verify Your account Email')
->action('Verify Account', route('verify', $this->user->token))
->line('Thank you for using our application!');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toTextlocal($notifiable)
{
return (new TextlocalMessage())
//Required
// To send sms via your Textlocal transactional account
//or promotional() to sent via Textlocal promotional account
->transactional()
//Required
//When sending through Textlocal transactional account, the content must conform to one of your approved templates.
->content("Use" . $this->user->code . "as your login OTP. OTP is confidential, Delish2go never call you for asking OTP. It valid for next 10 mins. Do not disclose OTP to anyone.");
}
public function toArray($notifiable)
{
return [
//
];
}
}
My RegisterController.php
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'token' => str_random(25),
'phone' => $data['phone'],
'code' => substr(str_shuffle("0123456789"), 0, 5),
]);
$user->sendVerificationEmail();
return $user;
}
My User.php Model
<?php
namespace App;
use App\Notifications\verifyEmailNotification;
use App\Notifications\SendBlackFridaySaleAnnouncement;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'token', 'id_name', 'email_id', 'phone', 'pass', 'code',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function verified()
{
return $this->token === null;
}
public function sendVerificationEmail()
{
$this->notify(new verifyEmailNotification($this));
}
}
Here is my Config/services.php
'textlocal' => [
'url' => 'https://api/textlocal.in/send' //or 'https://api.textlocal.in/send/ - for India
],
'transactional' => [
'apiKey' => env('TEXTLOCAL_TRANSACTIONAL_KEY'),
'from' => env('TEXTLOCAL_TRANSACTIONAL_FROM', 'TXTLCL')
],
My .env file
TEXTLOCAL_TRANSACTIONAL_KEY= My Api Key
TEXTLOCAL_TRANSACTIONAL_FROM=TXTLCL
My Composer.json
"require": {
"thinkstudeo/textlocal-notification-channel": "^1.0"
},
Please Help me, I have tried many things but my problem have not solved.
Have you tried using the Laravel SMS API plugin? It has built-in notification channel support as well. Here's a sample config for TextLocal which you can use with the plugin.
'textlocal' => [
'method' => 'POST',
'url' => 'https://api.textlocal.in/send/?',
'params' => [
'send_to_param_name' => 'numbers',
'msg_param_name' => 'message',
'others' => [
'apikey' => 'YOUR_API_KEY',
'sender' => 'YOUR_SENDER_NAME',
],
],
'json' => true,
'add_code' => false, //(If the numbers saved in DB do not have country code, change to true)
]
Hope it helps!

How to add username in welcome email after registration?

I've been searching everywhere for a solution to my issue. I've created a welcome email, created the Mailable, Controller, and View. But for some reason, the $user isn't showing in the email itself. It's blank. Am I missing something?
Mailable
<?php
namespace App\Http\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class Welcome extends Mailable
{
use Queueable, SerializesModels;
public $user;
/**
* #return void
*/
public function _construct(User $user)
{
$this->user = $user;
}
/**
*#return $this
*/
public function build()
{
return $this->view('emails.welcome')->subject('Welcome to');
}
}
Controller
<?php
namespace App\Http\Controllers\Auth;
use Mail;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Auth;
use App\Http\Mail\Welcome;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'mobile' => 'required',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'mobile' => $data['mobile'],
'password' => bcrypt($data['password']),
'payment_mode' => 'CASH',
]);
Mail::to($data['email'])->send(new Welcome($user));
return $user;
// send welcome email here
}
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
return view('user.auth.register');
}
}
View (shortened to show problem)
Welcome {{ $user->first_name }}
User
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens,Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'mobile', 'picture', 'password', 'device_type','device_token','login_by', 'payment_mode','social_unique_id','device_id','wallet_balance'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'created_at', 'updated_at'
];
}
As was mentioned, everything passes successfully, however, in the email itself, the name of the user is blank. Please help!
I got it working for anyone else dealing with same issue. I changed the register controller and just skipped the mailable entirely. In other words, I didn't need a separate mailable. Below is the result.
Mail::send('emails.welcome', [
'first_name' => $data['first_name'],
'email' => $data['email']
], function ($mail) use($data) {
$mail->from('Whatever', 'site/company name');
$mail->to($data['email'])->subject('Whatever');
});
return $user;
And in the view I just pass the first name like so
Welcome {{ $first_name }}

User authentication in laravel using middleware

I have a question about the built in user authentication functionality in laravel. I got the authentication part to work but it doesn't seem like a user is stored in the session.
Admin Controler Code:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator, Input, Redirect;
use DB;
use Session;
class AdminController extends Controller
{
public function index(Request $request)
{
if(isset($_POST['submit'])){
$v = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
],
[
'required' => 'This field is required.'
]);
if ($v->fails())
{
$messages = $v->messages();
return redirect()->back()->withErrors($v)->withInput();
}
else
{
$email = $request->input('email');
$pass = $request->input('password');
$whereData = [
['email',$email],
['password',md5($pass)]
];
$res = DB::table('tbl_admin_users')->where($whereData)->get();
if(!empty($res)){
$userid=$res[0]->id;
$fname=$res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
return Redirect('admin/dashboard-listing');
}
else
{
Session::flash('message', 'Email/Password is invalid!');
Session::flash('alert-class', 'alert-danger');
return Redirect('admin/login');
}
}
}
else{
return view('admin.admin-login');
}
}
public function logout()
{
Session::flush();
return Redirect('admin/login');
}
}
Middleware Authentication.php code:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController I have:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Route after correct details and login page route:
Route::get('/admin/dashboard-listing',array('uses'=>'Admin\AdminDashboardController#index'));
After logout redirect route:
Route::get('/admin/login',array('uses'=>'Admin\AdminController#index'));
My question is that how can i use middleware in this code. because
after logout i can easily access the url .back button is also worrking
i want laravel user authentication through middleware ..
You need to manually login user with auth()->login():
$res = DB::table('tbl_admin_users')->where($whereData)->first();
if(!empty($res)) {
$userid = $res[0]->id;
$fname = $res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
auth()->login($res);
return Redirect('admin/dashboard-listing');
}
Alternatively, you can use the auth()->loginById($res->id) method.

Laravel 5.1 FatalErrorException in RegistersUsers.php line 32

since a few time I started programming in Laravel for a schoolproject. Now I tried to implement a login system. My database for userinformation is running on my homestead virtual machine, running with Postgresql. I already migrated the tables, so they exist and the database is running. Problem is: When I fill in the registrationform and send it, I get an error:
FatalErrorException in RegistersUsers.php line 32: Call to a member function fails() on null
You can see the code of RegistersUsers.php underneath:
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
trait RegistersUsers
{
use RedirectsUsers;
/**
* Show the application registration form.
*
* #return \Illuminate\Http\Response
*/
public function getRegister()
{
return view('auth.register');
}
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
}
When I try to log in it gives the warning the log in credentials doesn't exist in the database (because I haven't registered yet), so it seems that the database connection works properly.
Does someone know a solution for this?
----UPDATE----
Underneath I added my AuthController is included. You can also see my project on my github, so you can look into my other files if needed: https://github.com/RobbieBakker/LaravelProject56
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
if(!$validator->fails())
{
session(['email' => $data['email']]);
}
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
I eventually solved it just by commenting the function which called this error. I'm not sure if it's supposed to be solved like that, but my login system seems to work fine now.
Thanks for your support!
You forgot return validator instance from your validator function ))
protected function validator(array $data)
{
$validator = Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
if(!$validator->fails())
{
session(['email' => $data['email']]);
}
return $validator;
}
I had same error )
I think you need to "make" the validator.
try changing it to this..
$validator = $this->validator->make($request->all(), $rules);
see if that works...

Resources