auth()->user()->id is not working when I use it in controller using routes to api.php

Viewed 3073
public function store(Request $request)
    {
        $booking = ($request->isMethod('put')) ? Booking::findOrFail($request->booking_id) : new Booking;
        $booking->checkIn = $request->checkIn;
        $booking->checkOut = $request->checkOut;
        $booking->room_id = $request->room_id;
        $booking->user_id = auth()->user()->id;//not working

        if($booking->save()){
            return new BookingResource($booking);
        }
    }

Route::put('/booking','BookingsController@store');//api.php

Here auth()->user()->id is not working but its working find if i use it the same code but route code in routes/web.php

3 Answers

pass guard parameter in auth used like that ..

1. auth('api')->user();  //if u are using api guard ...(web guard)
2. $request->user('api');     //by reqeust class
3. Auth::guard('api')->user()   //using Auth facade

use auth:api middleware in your route.

Route::middleware(['auth:api'])->put('/booking','BookingsController@store');

use this way in your controller :

use Illuminate\Support\Facades\Auth

$booking->user_id = Auth::user()->id;
Related