auth()->user()->pUserId 尝试在 null 上读取 属性 "pUserId"

auth()->user()->pUserId makes Attempt to read property "pUserId" on null

我遇到一个问题,在使用身份验证时我无法从数据库中获取 pUserId

这是控制器(Home Controller):

function index(){
    $id = Auth::user()->pUserId; //Here's the main problem
    $profiles = profiles::where('pUserId',$id)->first();
    return view('home', compact('profiles'));
    // return view('home');
}

auth.php(配置):

'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
]

User.php(型号)(laravel默认):

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    protected $table = 'profiles';
    protected $guarded = [''];

我已经尝试过不使用控制器并直接进入.blade.php,但错误仍然相同

@auth
<div class="header-control">
    <a href="">{{ auth()->user()->pUserId }}</a> //main problem
</div>
@endauth

The Error Display

路线如下:

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

Route::get('/', 'LoginController@index')->middleware('guest');
Route::get('/login', 'LoginController@index')->middleware('guest');
Route::post('/login/authenticate', 'LoginController@authenticate')->middleware('guest');

登录控制器:

function authenticate(Request $request)
{
    $login = $request->validate([
        'pUserId' => 'required',
        'password' => 'required'
    ]);

    if(Auth::attempt($login))
    {
        $request->session()->regenerate();
        return redirect()->intended('/home');
    }
    else
    {
        return back()->with('error', 'Wrong Login Details');
    }
}

配置文件表中有多个 pUserId,但在使用

时只是说“属性 "pUserId" on null"
auth()->user()->pUserId or 
$id = Auth::user()->pUserId;

Auth:attempt($login) 成功运行,我只是不明白它在 Home Controller 中不起作用

迁移:

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->string('pUserId',5)->primary();
        $table->string('pNamaLengkap', 255);
        $table->enum('pJobDescription', ['Full Stack Developer','Backend Developer','Frontend Developer']);
        $table->enum('pUnitKerja', ['Talent Management','Company Management','Customer Management']);
        $table->enum('pDirectorate',['Human Resources','Company Profile','Stabilitas Sistem Keuangan','Sistem Pengelolaan','Pendukung Kebijakan']);
        $table->string('password', 255);
        $table->timestamps();
    });
}

DB profiles

在您的用户模型中,如果您不使用 id 作为主键,请指定主键:

protected $primaryKey = 'pUserId';