skip to Main Content

this my laravel Task Controller

<?php

namespace AppHttpControllers;

use AppModelstask;
use AppModelsUser;
use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesValidator;

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:UsersLenovoBackendBSIMonitoringappHttpControllersTaskController.php on line 37

2

Answers


  1. 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

    Login or Signup to reply.
  2. To get id of the user authenticated you can use

    Auth::id()
    

    or use helper function

    auth()->id()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search