Laravel sending e-mails to new registered users - laravel

I'm trying to send e-mails to new users. I made changes in my env. file. I am using a gmail.com mail service. I want to send e-mails to users including their name. Ex:
Hi John, your registration is succesful!
Here John part will be user name.
my code is here in RegistrationController:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$to_name = $data['name'];
$to_email= $data['email'];
$body =[];
$mailData=array('body'=>$body);
Mail::send('email.email-register', $mailData, function($message) use ($to_name, $to_email ){
$message->to($to_email, $to_name)->subject('Registration is succesfull!');
$message->from(env('MAIL_USERNAME'));
});
return $user;
}
Also i am using a mail template. I want to send user as variable to the view. How do i do that?

1- You need to run command php artisan make:mail RegisterMail
2- Add Library use App\Mail\RegisterMail;
Mail::to('YourEmail#gmail.com')->send(new RegisterMail($mailData));
3- Create a new Data Member in your App\Mail\RegisterMail.php Class
public $mailData;
public function __construct($mailData)
{
$this->mailData = $mailData;
}
4- Add this in your App\Mail\RegisterMail.php
public function build(){
return $this->from('youremail#gmail.com','your name')->replyTo('youremail#gmail.com')->subject($this->mailData['subject'])->view('email')->with('mailData',$this->mailData);
}

Related

How To Get Auth ID form user table and grab it for store to other table on database

I want to get Auth ID from user who has logged in and then use the Auth ID to store on other table
User_detail Controller
this is my store function
$data = new ModelUser();
$user= new user();
$data->fill(Auth::user());
$data->id_user = Auth::get('id');
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
and this is function Login
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
$data = user::where('email',$email)->first();
if($data) //check email apakah ada atau tidak
{
if(Hash::check($password,$data->password))
{
Session::put('id',$data->id);
Session::put('full_name',$data->full_name);
Session::put('email',$data->email);
Session::put('login',TRUE);
return redirect('userdt');
}
else
{
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
}
}
this is the routes files
Route::get('/index','UserController#show')->name('surevey.index');
Route::get('/logout','UserController#Logout')->name('user.logout');
Route::post('/registerpost','UserController#RegisterPost')->name('user.register');
Route::post('/loginpost','UserController#LoginPost')->name('user.login');
//reward routes
Route::get('/reward','RewardController#index')->name('reward.list');
//profile
Route::put('/editprofile/edit/{id}','UserController#edit')->name('profile.edit');
Route::post('/editprofile/update','UserController#update')->name('profile.update');
Route::get('/userdt',['middleware'=>'auth','uses'=>'UserController#userdetail'])->name('userdt.show');
Route::post('/userdt/store','UserController#store')->name('userdt.store');
//Survei
Route::get('/createsurvey','SurveyController#show')->name('survey.create');
Route::get('/surveylist','SurveyController#index')->name('survey.list');
Auth::routes();
ModelUser
protected $fillable = [
'id_user',
'jenis_kelamin',
'no_tlp',
'jurusan',
'wilayah'
];
protected $table ='user_detail';
public function user()
{
return $this->belongsTo(user::class);
}
and I get error like this
Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must
be of the type array, null given, called in
E:\Laravel\surevey\app\Http\Controllers\UserController.php on line 110
You don't need to use $data->fill(Auth::user()); as you have only single user_id field need to set.
Also you can get the current logged in user's id using. \Auth::user()->id
So your code would be as follow:
$data = new ModelUser();
$data->id_user = \Auth::user()->id;
$data->jenis_kelamin = $request->jenis_kelamin;
$data->no_tlp = $request->no_tlp;
$data->jurusan = $request->jurusan;
$data->wilayah = $request->wilayah;
$data->save();
return redirect()->route('surveylist');
Note: Make sure you have included auth middleware with your route.
Like:
Route::get('profile', ['middleware' => 'auth', function() {
// Only authenticated users may enter...
}]);
And you have followed the authuntication process carefully.
https://laravel.com/docs/5.2/authentication
Edited:
Your loging should be changed as:
public function LoginPost(Request $request)
{
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('userdt');
}
return redirect('index')->with('alert','Password atau Email yang anda masukan salah !!! ' );
}
If your reverse one-to-one relationship in the User Model looks like this:
public function detail()
{
return $this->hasOne(ModelUser::class);
}
And you are sure a user is logged in, you could simply do this
$data = Auth::user()->detail()->save($request->all());
return redirect()->route('surveylist');
Laravel's ORM takes care of the rest.
should be Auth::id() or Auth::user()->id but seems like your Auth::user() is returning a null.make sure you sessions, routes are set up properly.
use Auth::attempt()to login user

How to login with google using socialite in laravel 5.8 with different types of users

I want to login with google socialite for two types of user.
1- Company Users.
2- Individuals users
In database users table i add a field sign_up_as if 1 then company users if 2 then individuals. so how i paas 1 and 2 value to signin with google link.
In the login view i add this code
<li>
<i class="fa fa-google"></i>
</li>
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Socialite;
use App\Services\SocialGoogleAccountService;
use Illuminate\Routing\UrlGenerator;
class SocialAuthGoogleController extends Controller
{
public function redirect()
{
return Socialite::driver('google')->redirect();
}
public function callback(SocialGoogleAccountService $service)
{
$user = $service->createOrGetUser(Socialite::driver('google')->user());
auth()->login($user);
return redirect()->to('/home');
}
}
createOrGetUser function
public function createOrGetUser(ProviderUser $providerUser)
{
// dd('now here');
$account = SocialGoogleAccount::whereProvider('google')
->whereProviderUserId($providerUser->getId())
->first();
// dd($account);
if ($account) {
return $account->user;
} else {
$account = new SocialGoogleAccount([
'provider_user_id' => $providerUser->getId(),
'provider' => 'google'
]);
$user = User::whereEmail($providerUser->getEmail())->first();
if (!$user) {
$user = User::create([
'email' => $providerUser->getEmail(),
'name' => $providerUser->getName(),
'password' => md5(rand(1, 10000)),
'sign_up_as' => 2, // currently sign_up-as static
]);
}
$account->user()->associate($user);
$account->save();
return $user;
}
}
I got the solution myself rather then passing values simple set the values in the session and get in the controller then save in the database like.
#php
session(['sign_up_as' => '2']);
#endphp
and in the controller
$sign_up_as = session('sign_up_as');

how to getting the email verification link in Unit Test Laravel

I am developing a Laravel application. I am doing unit testing to my application. Now I am having a trouble with testing the verification process.
What I am trying to do now is that I am registering a user, then test if the verification email is sent, then I will get the verification link for that registration, then I will do something with that link.
The first issue is that the email is not sent.
The second issue is that I do not know how to retrieve the
verification email link?
This is my test
public function test_user_can_be_verified_and_redirected_based_on_role()
{
Notification::fake();
$user = $this->registerUser();
Notification::assertSentTo($user, SendEmailVerificationNotification::class);
}
protected function registerUser()
{
$user = factory(User::class)->make();
$this->post(route('register'), [
'name' => $user->name,
'email' => $user->email,
'password' => 'testing',
'password_confirmation' => 'testing',
])->assertRedirect();
return User::whereEmail($user->email)->first();
}
But the issue is that the notification is not sent even if it is sent when I register from the browser. I also like to retrieve the verification link and do something. How can I do that?
Not a perfect solution but it does the trick, if somebody breaks this functionality somehow I'll know about it. :)
First overwrite the protected method verificationUri of the VerifyEmail notification and make it public
class EmailVerificationNotification extends VerifyEmail
{
public function verificationUrl($notifiable) {
return parent::verificationUrl($notifiable);
}
}
Then use it to generate a link and assert against it..
/** #test */
public function an_user_can_verify_his_email_address()
{
$notification = new EmailVerificationNotification();
$user = factory(User::class)->create(['email_verified_at' => null]);
$uri = $notification->verificationUrl($user);
$this->assertSame(null, $user->email_verified_at);
$this->actingAs($user)->get($uri);
$this->assertNotNull($user->email_verified_at);
}
A verification URL can be generated outside of the VerifyEmail notification easily by simply running:
$verificationUrl = URL::temporarySignedRoute(
'verification.verify',
now()->addMinutes(60),
['id' => $user->id, 'hash' => sha1($user->email)]
);
No need to make the verificationUrl() method public.
Here is my solution:
public function testVerifyEmailValidatesUser(): void
{
// VerifyEmail extends Illuminate\Auth\Notifications\VerifyEmail in this example
$notification = new VerifyEmail();
$user = factory(User::class)->create();
// New user should not has verified their email yet
$this->assertFalse($user->hasVerifiedEmail());
$mail = $notification->toMail($user);
$uri = $mail->actionUrl;
// Simulate clicking on the validation link
$this->actingAs($user)
->get($uri);
// User should have verified their email
$this->assertTrue(User::find($user->id)->hasVerifiedEmail());
}

I build a user invitation system with Laravel it does not work

I am building a user invitation system with Laravel that does not work I have the error here email invitation after sending the email to the user the descriptive image is lower Click here to activate!
my InviteController
public function process(Request $request)
{
// validate the incoming request data
do {
//generate a random string using Laravel's str_random helper
$token = str_random();
} //check if the token already exists and if it does, try again
while (Invite::where('token', $token)->first());
//create a new invite record
$invite = Invite::create([
'email' => $request->get('email'),
'token' => $token
]);
// send the email
Mail::to($request->get('email'))->send(new InviteCreated($invite));
// redirect back where we came from
return redirect()
->back();
}
public function accept($token)
{
// Look up the invite
if (!$invite = Invite::where('token', $token)->first()) {
//if the invite doesn't exist do something more graceful than this
abort(404);
}
// create the user with the details from the invite
User::create(['email' => $invite->email]);
// delete the invite so it can't be used again
$invite->delete();
// here you would probably log the user in and show them the dashboard, but we'll just prove it worked
return 'Good job! Invite accepted!';
}
my image error
Do a dd of $invite before passing to the mail to make sure you have the records:
//create a new invite record
$invite = Invite::create([
'email' => $request->get('email'),
'token' => $token
]);
dd($invite);
// send the email
Mail::to($request->get('email'))->send(new InviteCreated($invite));
Then on InviteCreated make sure you store $invite on a public property so its available on the blade template:
class InviteCreated extends Mailable{
public $invite;
public function __construct($invite){
$this->invite = $invite;
}
...... if you use markdown then pass the `$invite`..
public function build()
{
return $this
->markdown(your markdown mail')
->with([
'invite'=>$this->invite
]);
}
}

How to attach variable to reset password link view in laravel?

I am using laravel 5.2 where I need to sent an OTP code to reset password, though email is being sent with built in subject and limited message done by make:auth command but how to customize? I have tried to follow the link unfortunately I am unable to understand how i can use this to solve.
I customized the api like this
public function sendResetLinkEmail(Request $request)
{
$this->validateSendResetLinkEmail($request);
$broker = $this->getBroker();
$email = $request->input('email');
$userid = DB::table('users')->where('email','=',$email)->value('id');
$uniqueotp = "DIYA".uniqid();
$curr_timestamp = strtotime(date("Y-m-d H:i:s"));
$date = strtotime("+7 day", $curr_timestamp);
$expiry_otp = date('Y-m-d H:i:s',$date);
$ip_address = $request->ip();
DB::table('otp_users')->insert([
'user_id' => $userid,
'status' => 0,
'otp_code' => $uniqueotp,
'ipaddress'=>$ip_address,
'expires_at'=>$expiry_otp
]);
$response = Password::broker($broker)->sendResetLink(
$this->getSendResetLinkEmailCredentials($request),
$this->resetEmailBuilder()
);
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->getSendResetLinkEmailSuccessResponse($request,$response);
case Password::INVALID_USER:
default:
return $this->getSendResetLinkEmailFailureResponse($response);
}
}
Any idea how I can achieve?
My required email message like this:
Hello, Tamaghna Banerjee Click here to reset your password:
Your OTP is: B16445512121
Reset Your Password through http://localhost/diya/public/password/reset/83baba9f61fc851b9d80b515415ec86c43b03b56b068e1888256db7a7831ba83?email=tamaghnabanerjee%40live.com

Resources