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
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 loginDocumentation :
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
To get id of the user authenticated you can use
or use helper function