Home > Back-end >  Get Current user Login In Laravel 8
Get Current user Login In Laravel 8

Time:11-05

this my laravel Task Controller

<?php

namespace App\Http\Controllers;

use App\Models\task;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class TaskController extends Controller
{
 
    public function getTask()
    {
        $userid=  Auth::user()->id;
        $response = task::where('id_karyawan',$userid)->get();
        return response()->json($response,200);
    }
  
}

but i get this error when i try it in postman. please help me to clear this error thanks

ErrorException: Trying to get property 'id' of non-object in file C:\Users\Lenovo\BackendBSIMonitoring\app\Http\Controllers\TaskController.php on line 37

CodePudding user response:

There are two things you need to check

First : Check if there is any user logged in currently

If user is not authenticated then Auth::user() will not work.

Second : Check if you have used Auth Middleware in routes and while performing login

Documentation :

Routes : https://laravel.com/docs/9.x/authentication#protecting-routes

Authenticate users : https://laravel.com/docs/9.x/authentication#authenticating-users

Check if current user is authenticated or not : https://laravel.com/docs/9.x/authentication#determining-if-the-current-user-is-authenticated

CodePudding user response:

To get id of the user authenticated you can use

Auth::id()

or use helper function

auth()->id()
  • Related