Laravel 身份验证登录不起作用

2024-02-10

我是 Laravel 的新手,我正在开发 Laravel 身份验证系统,虽然注册有效,但登录没有执行任何操作。

用户控制器.php

class UserController extends Controller
{

    public function postSignUp(Request $request)
    {


        $email = $request['email'];
        $first_name = $request['first_name'];
        $password = bcrypt($request['password']);

        $user = new User;

        $user->email = $request->email;
        $user->first_name = $request->first_name;
        $user->password = bcrypt($request->password);

        $user->save();

        Auth::login($user);

        return redirect()->route('hotelier.index')->with('alert-success','Data has been saved successfully');


    }


    public function postSignIn(Request $request)
    {

        if(Auth::attempt(['email' => $request['email'], 'password' => $request['password']])){

            return redirect()->route('hotelier.index');

        }

         return redirect()->back();

    }

}

路线(web.php)

    Route::group(['middleware' => ['web']], function (){

        Route::get('/', function () {
            return view('welcome');
        });

        Route::resource('hotelier','HotelierController');

            Route::post('/signup', [

            'uses'=> 'UserController@postSignUp',
            'as' =>'signup'

        ]);


        Route::post('/signin', [

            'uses'=> 'UserController@postSignIn',
            'as' =>'signin'

        ]);


    } );

   Auth::routes();

   Route::get('/home', 'HomeController@index')->name('home');

请告诉我如何登录

Thanks


您应该只使用 artisan 命令 php artisan make:auth。这将创造一些东西。它将在您的 Controllers 文件夹和 view 文件夹中创建一个 auth 文件夹。假设您使用的是 laravel 5.4,它还会添加到您的 web.php 路由文件中。在你的controller/auth目录中你会找到你的LoginController和RegisterController。它实际上应该拥有您进行身份验证所需的一切。您需要确保您的用户模型上有电子邮件或用户名属性。您还需要有一个密码属性。从那里您可能需要根据您的应用程序进行一些自定义。

这是一个登录控制器示例:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/customer';

    /**
     * Create a new controller instance.
     *
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');

    }

    protected $username = 'email';

    public function loginNameOrEmail(Request $request)
    {
        $field = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL) ? 'email_address' : 'username';

        $request->merge([$field => $request->input('email')]);

        $this->username = $field;

        return $this->login($request);

    }


    public function username()
    {
        return $this->username;
    }

}

注册控制器:

<?php

namespace App\Http\Controllers\Auth;

use App\Email;
use App\PersonName;
use App\Location;

use App\Contact;

use App\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
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.
     *
     */
    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|string|max:255',
            'middle-name' => 'required|string|max:255',
            'last-name' => 'required|string|max:255',
            'address' => 'required|string|max:255',
            'city' => 'required|string|max:255',
            'state' => 'required|string|max:255',
            'email' => 'required|string|email|max:255',
            'password' => 'required|string|min:4|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {

        $email_address = $data['email'];

        $email = new Email();

        $email->setEmail($email_address);


        $location = new Location([
            'address'   =>  $data['address'],
            'city'      =>  $data['city'],
            'state'     =>  $data['state'],
            'zipcode'   =>  $data['zip']
        ]);

        $location->save();

        $location->createCoordinates();

        $personname = new PersonName([
            'first_name'        =>  $data['first-name'],
            'last_name'         =>  $data['middle-name'],
            'middle_name'       =>  $data['last-name'],
            'preferred_name'    =>  $data['preferred-name'],
            'title'             =>  $data['title']
        ]);

        $personname->save();

        $contact = new Contact();

        $contact->email_id = $email->id;
        $contact->location_id = $location->id;
        $contact->personname_id = $personname->id;

        $contact->save();

        $user = new User();
        $user->contact_id = $contact->id;
        $user->email_address = $email_address;
        $user->setPassword($data['password']);
        $user->username = $user->getEmailUsername();
        $user->save();




        return $user;
    }
}

路线/web.php:

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function(){
   return view('auth.login');
});

Auth::routes();

Route::post('login', 'Auth\LoginController@loginNameOrEmail');
//Route::get('/test')

// auth middleware //

Route::group(['middleware' => ['auth']], function () {

    // Enums Route //

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/dashboard', 'DashboardController@index')->name('dashboard');


Route::get('/customer', 'CustomerController@index');

Route::post('/customer', 'CustomerController@show');

Route::get('/titleEnum', 'EnumController@title');

Route::get('/genderEnum', 'EnumController@gender');

Route::get('/test', 'TestController@test');


});

为什么不使用用户模型:

<?php

namespace App;


use Mockery\Exception;
use Illuminate\Support\Facades\Hash;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

use App\Model as Model;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{

    use Authenticatable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'contact', 'username', 'email_address'
    ];

    /**
     * The column name of the "remember me" token.
     *
     * @var string
     */
    protected $rememberTokenName = 'remember_token';

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'remember_token', 'active'
    ];

    /**
     * the attributes that should be guarded from Mass Assignment
     *
     * @var array
     */
    protected $guarded = [
        'created_at', 'updated_at', 'password_hash'
    ];

    /**
     * Define table to be used with this model. It defaults and assumes table names will have an s added to the end.
     *for instance App\User table by default would be users
     */
    protected $table = "user";

    /**
     * We have a non incrementing primary key
     *
     * @var bool
     */
    public $incrementing = false;

    /**
     * relationships
     */
    public function contact(){
//        return $this->hasOne(Contact::class, 'id', 'contact_id');
        return $this->hasOne(Contact::class);
    }


    public function customers(){
//        return $this->hasOne(Contact::class, 'id', 'contact_id');
        return $this->hasMany(Customer::class);
    }

    /**
     * User constructor.
     * @param array $attributes
     */
    public function __construct($attributes = array())  {
        parent::__construct($attributes); // Eloquent
        // Your construct code.

        $this->active = 1;

        return $this;
    }


    /**
     * @param $password string
     * set user password_hash
     * @return $this
     */
    public function setPassword($password){
        // TODO Password Validation
        try{
            $this->isActive();
            $this->password_hash = Hash::make($password);
            $this->save();
        } catch(\Exception $e) {
            dump($e->getMessage());
        }
        return $this;
    }


    /**
     * Returns whether or not this use is active.
     *
     * @return bool
     */
    public function isActive(){
        if($this->active) {
            return true;
        } else {
            Throw new Exception('This user is not active. Therefore you cannot change the password', 409);
        }
    }


    public function getEmailUsername(){
        $contact = Contact::getObjectById($this->contact_id);

        $email = Email::getObjectById($contact->email_id);

        return $email->username_prefix;
    }


    /**
     * @return string
     *
     * getFullName
     * returns concatenated first and last name of user.
     */
    public function getFullName(){
        return $this->first_name . ' ' . $this->last_name;
    }


    /**
     * Get the name of the unique identifier for the user.
     *
     * @return string
     */
    public function getAuthIdentifierName(){
        return $this->getKeyName();

    }

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier(){
        return $this->{$this->getAuthIdentifierName()};
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword(){
        return $this->password_hash;
    }

    /**
     * Get the token value for the "remember me" session.
     *
     * @return string
     */
    public function getRememberToken(){
        if (! empty($this->getRememberTokenName())) {
            return $this->{$this->getRememberTokenName()};
        }
    }

    /**
     * Set the token value for the "remember me" session.
     *
     * @param  string  $value
     * @return void
     */
    public function setRememberToken($value){
        if (! empty($this->getRememberTokenName())) {
            $this->{$this->getRememberTokenName()} = $value;
        }
    }

    /**
     * Get the column name for the "remember me" token.
     *
     * @return string
     */
    public function getRememberTokenName(){
        return $this->rememberTokenName;
    }

    /**
     * Get the e-mail address where password reset links are sent.
     *
     * @return string
     */
    public function getEmailForPasswordReset(){

    }

    /**
     * Send the password reset notification.
     *
     * @param  string  $token
     * @return void
     */
    public function sendPasswordResetNotification($token){

    }

    public function validateAddress(){

    }


}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 身份验证登录不起作用 的相关文章

  • laravel中过滤后如何导出excel?

    我想仅导出视图刀片中过滤的数据 我正在使用 Laravel 7 和 maatwebsite excel 3 1 和 PHP 7 4 2 我浏览了文档并应用了这个 View a href class btn btn success i cla
  • 合并 csv 文件 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 如何在 PHP 或 joomla 中将多个 CSV 文件合并为一个 csv 文件 将文件夹中 csv 文件中的所有数据合并到文本文件中 通
  • 一些基本的 PHP 问题 [已关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我只是有一些基本的 php 问题来加深我对学习的理解 但我找不到简单的答案 我有一个 php ajax 应用程序 它生成 mysql
  • 如何使用 PHP 从内容中查找 URL?

    需要一个简单的 preg match 它将在内容中查找 c aspx 不带引号 如果找到 它将返回整个 url 举个例子 content div 4 a href m c aspx mt 01 9310ba801f1255e02e411d8
  • PHP:STR 替换为链接

    我有这个 PHP 聊天框 如果我在聊天框中键入链接 它不会将其显示为链接 我如何使用 STR 替换来执行此操作 它应该响应诸如 http http com nl www www 之类的内容 我的其他 STR 替换行如下所示 bericht
  • 如何在 Laravel 中 session_write_close() ?

    Running session write close before sleep 在 Laravel 中似乎不起作用 因为会话仍然被其他请求阻止 直到当前连接完成 我试图sleep 在 Laravel 中 不会阻止其他请求 发现 sessi
  • cakephp 1.1 与 php 5.3

    我刚刚从 php 5 1 升级到 5 3 之前在我的服务器上使用 cakephp 1 1 自从升级 或者可能更早 我不确定 以来 我收到以下错误 任何人都可以透露一些信息 Deprecated Assigning the return va
  • Symfony 学说错误“DoctrineMigrationsBundle 需要启用 DoctrineBundle。”

    我创建了一个新的 Symfony 项目 并且不断收到此消息 DoctrineMigrationsBundle 需要启用 DoctrineBundle 错误并且无法摆脱它 显然我是这个星球上唯一一个收到此错误的人 因为谷歌并没有太大帮助 在
  • HTTP_REFERER 返回 NULL,$_SERVER 中不存在密钥

    使用以来第一次 SERVER HTTP REFERER 它给了我NULL因此 当我做var dump SERVER the HTTP REFERER密钥不存在 我还尝试使用不同的浏览器和不同的网站访问网站 但没有结果 该网站在基于 Linu
  • 拉拉维尔; “SQLSTATE[HY000] [2002] 连接被拒绝”

    我在 OSX 主机上设置了 homestead 2 0 并使用 Sequel Pro 我可以进行迁移并确认数据已在Sequel Pro中迁移 因此看起来数据库连接没有问题 但是 一旦我尝试从 Laravel 4 2 应用程序获取数据 它就无
  • .htaccess 在动态文件夹名称中加载索引

    我在 htaccess 加载动态文件夹名称中的索引时遇到问题 这是我的目录结构 root products gt this is constant folder name 而不是使用 GET 获取产品 url root products i
  • MySQL:“您的 SQL 语法错误...靠近键...”? [关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我发现了一个非常酷的用于丢失密码的脚本 但是这一行给我带来了问题 r mysql query INSERT INTO keys u
  • 返回上一页

    我正在使用表格来 评价 页面 此表单将数据 发布 到其他地方的 php 脚本 我只是想在处理表单后显示一个链接 这将使用户返回到上一页 我可以在 php 脚本中使用 javascript 来执行此操作吗 GF 您可以使用链接来调用histo
  • 如何使用额外标记输出 wp_list_categories

    我目前正在使用下面的脚本在无序列表中输出我的所有 WordPress 类别 如何获得带有额外标记的输出 ul ul 例如 ul li Category 1 rsaquo li li Category 2 rsaquo li ul 代替 ul
  • 如何让Symfony2直接加载CSS、JS文件而不是通过PHP?

    老问题 请参阅下面的更新版本 我的开发环境不是最快的 每个 PHP 请求大约需要 500 毫秒 它开始成为 Symfony2 资源文件的问题 因为每个资源文件都是通过 Symfony 的内部控制器请求的 http localhost myp
  • 从文本文件 PHP 读取数据

    我只是想知道如何在 php 中读取文本文件 我想让它显示文本文件中的最后 200 个条目 每个条目都在一个新行上 Like John White Jane Does John Does Someones Name 等等 Thanks Use
  • PHP OOP 静态属性语法错误 [关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 为什么不
  • 将单独的月、日和年值转换为时间戳

    我有月份值 1 12 日期值 1 31 和年份值 2010 2011 2012 我还有一个小时值和一个分钟值 我怎样才能把这个给strtotime 它可以以某种方式将其转换为时间戳吗 当您已经知道年月和日期时 为什么将字符串转换为日期 us
  • 如何使用多个数据库设置 symfony 3 学说迁移?

    我在验证和更新模式时努力让 symfony doctrine 排除数据库视图 我第一次尝试没有教条迁移 看到这个问题 https stackoverflow com questions 46775200 symfony 3 doctrine
  • 如何检查号码是否是巴基斯坦用户的手机号码而不是固定电话号码

    我所做的是从开头删除 92 或 0092 并使用以下代码检查它是否是巴基斯坦人的有效手机号码 if preg match 3 0 4 0 9 number 1 Pakistani mobile number else not a pakis

随机推荐