2
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

Rahul Shakya
  • 1,269
  • 15
  • 15
  • Possible duplicate of [Laravel 5.6 - How to get auth()->user() or $response->user() in api controller?](https://stackoverflow.com/questions/50709659/laravel-5-6-how-to-get-auth-user-or-response-user-in-api-controller) – miken32 Nov 17 '18 at 02:50

3 Answers3

4

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
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
1

use auth:api middleware in your route.

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

use this way in your controller :

use Illuminate\Support\Facades\Auth

$booking->user_id = Auth::user()->id;
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71