Laravel 注册登录 user Model 使用 uuid 的坑

问题 : 注册,登录正常,跳转后,Auth::user(); 获取不到用户实例

解决办法:


  public $incrementing = false;

   /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'uuid';

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'varchar';

网上看的说是 $guard 不同的原因,dd后发现使用的都是‘web’的guard

查看源码
namespace Illuminate\Auth;

trait Authenticatable{
   /**
     * 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()};
    }
}

继续追踪

namespace Illuminate\Database\Eloquent;
abstract class Model implements ArrayAccess, Arrayable, Jsonable, JsonSerializable, QueueableEntity, UrlRoutable
{

  /**
     * The primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'int';

  /**
     * Get the primary key for the model.
     *
     * @return string
     */
    public function getKeyName()
    {
        return $this->primaryKey;
    }
}

果然,直接百度是不行的,还是查看源码才是根本

本作品采用《CC 协议》,转载必须注明作者和本文链接
喜欢的话就点个赞吧!
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3

就不建议使用uuid作为用户id。

5年前 评论

这个难道不可以将主键ID的值为uuid的形式,而不改变字段的名字,还用id吗?

$table->uuid('id');
5年前 评论

@Alexanderwmc 可以的 更改id字段的类型就好,数据库也做调整

protected $keyType = 'varchar';

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!