how to access Auth('api')->user() in API resource controller using passport

280 Views Asked by At

My Controller

<?php
    
    namespace App\Http\Controllers\Api;
    
    use App\User;
    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use App\Http\Resources\BlogCollection;
    
    class BlogLikeController extends Controller
    {
    
        /**
         * Display a listing of the resource.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
           $user = auth('api')->user();
           
           return new BlogCollection($user);
        }
    }

Routes

Route::middleware('auth:api')->group(function () {
    Route::apiResource('bloglike','Api\BlogLikeController');
});

Result

The result shows incorrect value

I am using vue.js to return values to be saved through my recipient resource and I would like to save it along with my user_id using Auth::user()->id; Unfortunately I always get 0 in my user_id because I cannot access Auth('api')->user()->id in my API resource controller

1

There are 1 best solutions below

0
On

This should work

$user = User::where('id', auth('api')->user()->id)->get();
$user = BlogCollection::collection($user);