How to send mail after Laravel 5 default registration?
Asked Answered
E

2

21

I'm noob in Laravel and working with Laravel 5. For user registration and and login, I want to use default system of laravel. But, need to extend it with two following features:

  1. User will get an email just after registration.
  2. Upon saving of user registration, I need to make an entry in another role table (I've used Entrust package for role management)

How to do these things?

Effort answered 20/3, 2015 at 18:3 Comment(1)
Look at services/registrar.phpJusten
J
34

You can modify Laravel 5 default registrar located in app/services

<?php namespace App\Services;

    use App\User;
    use Validator;
    use Illuminate\Contracts\Auth\Registrar as RegistrarContract;
    use Mail;

    class Registrar implements RegistrarContract {

        /**
         * Get a validator for an incoming registration request.
         *
         * @param  array  $data
         * @return \Illuminate\Contracts\Validation\Validator
         */
        public function validator(array $data)
        {
            return Validator::make($data, [
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|confirmed|min:6'
            ]);
        }

        /**
         * Create a new user instance after a valid registration.
         *
         * @param  array  $data
         * @return User
         */
        public function create(array $data)
        {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => \Hash::make($data['password']),
                //generates a random string that is 20 characters long
                'verification_code' => str_random(20)
            ]);

//do your role stuffs here

            //send verification mail to user
            //---------------------------------------------------------
            $data['verification_code']  = $user->verification_code;

            Mail::send('emails.welcome', $data, function($message) use ($data)
            {
                $message->from('[email protected]', "Site name");
                $message->subject("Welcome to site name");
                $message->to($data['email']);
            });


            return $user;
        }

    }

Inside resources/emails/welcome.blade.php

Hey {{$name}}, Welcome to our website. <br>
Please click <a href="{!! url('/verify', ['code'=>$verification_code]) !!}"> Here</a> to confirm email

NB: You need to create route/controller for verify

Justen answered 20/3, 2015 at 19:46 Comment(4)
Is modifying this file a bad idea? If composer updates Laravel would this file be overwritten?Marivaux
@Josh Mountain Not at all. Composer only updates Laravel Framework located in vendor directoryJusten
Your 'verification_code' generated randomly from your model? Or just filled the default method on migration file?Trommel
@Trommel my verification_code is generated when user signs up for an account. Its a unique random string. Doing it at model like so: public function setVerificationCodeAttribute($value) { $this->attributes['verification_code'] = md5(str_random(64) . time()*64); }Justen
C
18

Laravel has an empty method named registered in Illuminate\Foundation\Auth\RegistersUsers trait to simplify this operation, just override it as following:

First add a new Notification:

<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class UserRegisteredNotification extends Notification {

    public function __construct($user) {
        $this->user = $user;
    }

    public function via($notifiable) {
        return ['mail'];
    }

    public function toMail($notifiable) {
        return (new MailMessage)
            ->success()
            ->subject('Welcome')
            ->line('Dear ' . $this->user->name . ', we are happy to see you here.')
            ->action('Go to site', url('/'))
            ->line('Please tell your friends about us.');
    }

}

Add this use line to your RegisterController.php:

use Illuminate\Http\Request;
use App\Notifications\UserRegisteredNotification;

and add this method:

protected function registered(Request $request, $user) {
    $user->notify(new UserRegisteredNotification($user));
}

You are done.

Catlett answered 30/4, 2017 at 20:3 Comment(5)
where do you add new notification ??Selmner
Use artisan command: php artisan make:notification UserRegisteredNotificationCatlett
This is more laravel style way to do it than digilimit solution.Parrot
Why it is saying 'Undefined variable: user' at $this->user = $user in UserRegisteredNotificationSuper
I forgot to send $user in constructor. Now it is working.Super

© 2022 - 2024 — McMap. All rights reserved.