'Laravel 9: Auth::user() / auth()->user() null after successfull login

I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):

 route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

route::controller(UserController::class)->group(function () {
    route::post('/register', 'register');
    route::post('/login', 'login');
    route::get('/logout', 'logout');
});

route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);

successfull login

As you can see in the image above, I can get the authenticated user after try login it, here's my login method:

public function login(Request $request)
{
    $validate = $request->validate([
        'email' => 'required|email',
        'password' => 'required'
    ]);

    if ($validate) {
        $credentials = $request->only('email', 'password');

        return Auth::attempt($credentials)
            ? Auth::user() :
            response()->json('No se ha podido iniciar sesión', 500);
    }

    return response()->json($validate->errors, 422);
}

But when I'm going to store a new book, I get the following error:

id null

Here's the error, when I try to use the auth()->user() method to get the logged in user's id:

public function store(Request $request)
{
    $validate = $request->validate([
        'title' => 'required',
        'genre' => 'required'
    ]);

    if ($validate) {
        $book = Book::create([
            'title' => $request->title,
            'author' => $request->author,
            'genre' => $request->genre,
            'subgenre' => $request->subgenre,
            'opinion' => $request->opinion,
        ]);

        $user = User::find(auth()->user()->id);

        if ($request->cover) {
            $this->uploadImage($request, 'cover', $book);
        }

        $user->books()->save($book);

        return new BooksResource($book);
    }

I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:



Solution 1:[1]

From laravel 9 documentation

// Get the currently authenticated user's ID...
$id = Auth::id();

Also, you should describe your

route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);

route before resource route. I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user

Solution 2:[2]

To get the Authenticated user, put the book route inside the auth:sanctum middleware.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nika Simon
Solution 2 Justin