Laravel:如何通过登录注册用户?

时间:2018-05-07 08:30:27

标签: php laravel authentication login registration

我使用的是login/registration Auth控制器的标准方法。目标是在用户登录时注册一个新用户,如果没有这样的用户,或者只有auth,如果有的话。在我看来,应该简单地重新分配几种方法。首先,我改变了

AuthenticatesUsers.php

    public function login(Request $request)
    {
        $this->validateLogin($request);

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }


        $this->incrementLoginAttempts($request);

        //return $this->sendFailedLoginResponse($request);
    }

With commenting the last line it will not say that there is no such user, and I believe right there I should put register method, but I can't find the right way to include it. I suggest that I should use `RegisterUsers.php`

AuthenticatesUsers.php是执行登录逻辑的控制器。我们正在查看公共功能登录

    AuthenticatesUsers.php
    <?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Validator;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;

trait AuthenticatesUsers
{
    use RedirectsUsers, ThrottlesLogins, RegistersUsers;


    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $this->validateLogin($request);


        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }


        $this->incrementLoginAttempts($request);

        //return $this->sendFailedLoginResponse($request);
        $this->register($request);
    }

    public function register(Request $request)
    {
        $this->validator($request->all())->validate();

        event(new Registered($user = $this->create($request->all())));

        $this->guard()->login($user);

        return $this->registered($request, $user)
            ?: redirect($this->redirectPath());
    }

    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:6|confirmed',
        ]);
    }

    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->filled('remember')
        );
    }

    protected function credentials(Request $request)
    {
        return $request->only($this->username(), 'password');
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
                ?: redirect()->intended($this->redirectPath());
    }

    protected function authenticated(Request $request, $user)
    {
        //
    }

    protected function sendFailedLoginResponse(Request $request)
    {
        throw ValidationException::withMessages([
            $this->username() => [trans('auth.failed')],
        ]);
    }

    public function username()
    {
        return 'email';
    }

    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/');
    }

    protected function guard()
    {
        return Auth::guard();
    }
}

3 个答案:

答案 0 :(得分:2)

只需将register方法从RegisterUsers.php覆盖到您的LoginController

public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

同时添加来自validator的{​​{1}}受保护功能,并根据您的字段进行修改。

另请注意编辑RegisterController模型User数组以及创建fillable表的相对迁移文件。将users设置为Nullable()期间您不会输入的字段。

答案 1 :(得分:0)

在LoginController中实现此方法

const data = [
  {prop1: 11, prop2: 12, prop3: 13, prop4: 14},
  {prop1: 21, prop2: 22, prop3: 23, prop4: 24},
  {prop1: 31, prop2: 32, prop3: 33, prop4: 34}
];

// Assuming you are only interested in prop1 and prop2
const filteredResult = data.map(item => (
  {prop1: item.prop1, prop2: item.prop2}
));

console.log(filteredResult);

答案 2 :(得分:0)

我所要做的就是转向用户模型,无需指定任何方法 以下是AuthenticatesUsers.php中的函数应如何显示:

public function login(Request $request)
{
    $this->validateLogin($request);

    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);

        return $this->sendLockoutResponse($request);
    }

    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }

    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);

    //return $this->sendFailedLoginResponse($request);
    $user = User::where('email', '=', $_POST['email'])->first();
    if ($user === null) {
        return User::create([
            'name' => $_POST['email'],
            'email' => $_POST['email'],
            'password' => Hash::make($_POST['password']),
        ]);
    }
    else
        echo 'Wrong password';
}