Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ForeverAndADave's avatar

Get current user's ID in API Controller

So I've been going through a tutorial on using Vue Router and Laravel. All is well, but in the tutorial he doesn't add the currently logged in/authenticated user's ID to the table we are saving a form submission to. Normally, when using a regular controller, I would use something like auth()->id() to add in the ID. But when I try that in the API Controller, it is coming up null. So far everything I've tried via things I've googled have still ended up with a null. Anyone able to help me out? Thanks!

0 likes
17 replies
munazzil's avatar

Use as like below.

 auth('api')->user()->id
4 likes
ForeverAndADave's avatar

@MUNAZZIL - Hmmm... when I added that I am getting the following error in my Network XHR...

{message: "Trying to get property 'id' of non-object", exception: "ErrorException",…} exception: "ErrorException" file: "D:\www\xxx\app\Http\Controllers\API\XxxController.php" line: 50 message: "Trying to get property 'id' of non-object" trace: [{file: "D:\www\xxx\app\Http\Controllers\API\XxxController.php", line: 50,…

Any idea how to fix that? Thanks!

Eeetm's avatar

try to see in laravel.log

          Log::info(Auth::user());
ForeverAndADave's avatar

@MUNAZZIL -

Sure thing... here you go... (XxxController is actually TeacherController. I just renamed it to make it ambiguous)

API CONTROLLER...

<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Teacher;

class TeacherController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $attributes = $request->validate([
            'first_name' => 'required',
            'last_name' => 'required',
            'photo' => 'nullable|dimensions:max_width=500,max_height=500|size:5000',
            'dob' => 'nullable|date',
            'gender' => 'required',
            'email' => 'required|email|unique:teachers,email|max:255',
            'phone_1' => 'nullable|min:10|max:15',
            'phone_2' => 'nullable|min:10|max:15',
            'address' => 'nullable|max:255',
            'city' => 'nullable|max:255',
            'state' => 'nullable|max:2',
            'zip' => 'nullable|max:10',
            'hire_date' => 'required|date',
            'termination_date' => 'nullable|date',
            'rate' => 'nullable|integer',
            'notes' => 'nullable',
            'active' => 'required'
        ]);
        
        $attributes['user_id'] = auth('api')->user()->id; //Adds current user's id
        
        Teacher::create($attributes);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

MIGRATION...

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTeachersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('teachers', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->string('photo')->default('teacher.png');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('gender');
            $table->date('dob')->nullable();
            $table->string('phone_1');
            $table->string('phone_2')->nullable();
            $table->string('email');
            $table->string('address');
            $table->string('city');
            $table->string('state');
            $table->string('zip');
            $table->string('rate')->nullable();
            $table->string('hire_date');
            $table->string('termination_date')->nullable();
            $table->string('notes')->nullable();
            $table->boolean('active')->default(true);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('teachers');
    }
}
Eeetm's avatar

Pass the api guard as a parameter to fetch the authorized user without the middleware protecting the request.

$request->user('api');

// Or

auth('api')->user();
Eeetm's avatar

You can not get authenticated user when you are using RESP api .....

You have to pass it as request payload ...

1 like
munazzil's avatar

Use as like below and check.

     auth('api')->user()->user_id

or else try

          auth()->user()->id
shaikh709's avatar

Just a silly thing but make sure you are passing token correctly. Like if you are using passport or JWT. Then in your request header token should be present. You can open Chrome DevTools. click on network tab. Click on the request which was made to store data and then click on header. Headers and preview etc will popup when you click on request. Here is how you can find request header in case if you don't know https://developers.google.com/web/tools/chrome-devtools/network-performance/reference

In there your token should be passed to server correctly. At this moment your app is returning null when you call auth('api')->user(). So, it is thinking that you are not logged-in yet.

ForeverAndADave's avatar

@SHAIKH709 - I think you may be on the right track. I see in the tutorial that I'm following there is mention of implementing Passport and JWT (I have no idea what either of those are) in future episodes... so maybe I should just keep moving forward until I reach those areas? Being you mentioned that the app may not be thinking I'm actually logged in until I do that stuff.

I noticed that when I tried to add...

public function __construct()
    {
        $this->middleware('auth'); //ensures user is logged in
    }

to my controller, it was throwing an error that said message: "Unauthenticated." which is what makes me think you may be right.

Thoughts? :)

shaikh709's avatar

Yeah, That's what is happening. For the system, User is not logged in. checkout laravel passport. Something about tokens "APIs typically use tokens to authenticate users and do not maintain session state between requests.". So, Having token will solve your problem. follow guide on this link https://laravel.com/docs/5.7/passport and that should resolve your issue. It isn't really a issue at this moment your system lacks api token. That's it. :)

2 likes
csesumonpro's avatar

Laravel by default provide current user instance using laravel helper or laravel static method. Examle : default=>

\Auth::user();

if you used any guard for this then just used

 \Auth::guard('guard_name')->user();

If you used api then you can get current user by

auth('api')->user();  //it's a laravel helper

this one for api route above two for web route

estebanvp's avatar

I have the same problem how did you solve it ??

Please or to participate in this conversation.