在Laravel 5.2中向AuthController添加事件

时间:2016-12-07 22:15:03

标签: php laravel

在我想要帮助澄清之前,我看到了这个问题。

目标是在有人注册网站时触发事件。

我在事件服务提供商中添加了事件/侦听器对,如Laravel文档中所述。

然后我运行了:php artisan命令 php artisan generate:event

当用户在example.com/register上注册时,它应该触发该事件。但事实并非如此。

任何建议?

应用程序/ HTTP /控制器/认证/ AuthController.php

 protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
        Event::fire(new NewUserSignUp($data));
    }

整个文件:

<?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;
use App\Events\NotifyAdminSignUp;

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']),
    ]);
    Event::fire(new NewUserSignUp($data));
}



}

1 个答案:

答案 0 :(得分:1)

protected function create(array $data)
{ 
    //fire event BEFORE return
    Event::fire(new NewUserSignUp($data));
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
    //because nothing after this line will ever be processed

}