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

Time:12-02

I have a problem where i can't get the pUserId from database when using authentication

Here's the controller(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(config):

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

User.php(model)(default by laravel):

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

I've already tried without using controller and straight to .blade.php and the error is still the same

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

The Error Display

Here's the route:

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');

Login Controller:

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');
    }
}

There's a several pUserId in profiles tables, but just said "property "pUserId" on null" when using

auth()->user()->pUserId or 
$id = Auth::user()->pUserId;

Auth:attempt($login) is successfully working, i just don't understand it doesn't work in Home Controller

migrations:

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

CodePudding user response:

In your user model, specify the primary key if you don't use id as the primary key:

protected $primaryKey = 'pUserId';
  • Related