Chris Wickham
Chris Wickham

Reputation: 521

Auth::id() is null in Laravel api requests

I'm new to Laravel, and I've just set up my authentication using php artisan make:auth. I'm building a learning portal, and I'm trying to create a Subject against a user, but I'm not certain how to access the id of the current user correctly. I've been looking at similar issues are there seem to be numerous ways of writing authenticated calls, but I'm in uncertain of the best method. However, in my example,Auth::id() returns null. Can anyone advise on the best method of doing authenticated api calls?

use Illuminate\Http\Request;
use App\Subject;
use Illuminate\Support\Facades\Auth;

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

Route::get('subjects', function(){
    $subjects = Subject::with(['topics','topics.modules'])->where('user_id', Auth::id())->get();

    return $subjects;
});

Route::post('subjects', function(Request $data){
    if(isset($data->id)){
        $req = Subject::findOrFail($data->id);
        $req->update(['title'=>$data->title, 'subtitle'=>$data->subtitle]);
    }else{
        $new = Subject::create(['user_id'=> Auth::id(), 'title'=>$data->title, 'subtitle'=>$data->subtitle]);
        return $new->id;
    }
});

Route::delete('subjects/{id}', function($id){
    Subject::where('id', $id)->delete();
});

Upvotes: 0

Views: 1395

Answers (3)

Travis Britz
Travis Britz

Reputation: 5552

You need to send the rest of your routes through the auth:api middleware. Right now only your /user route is using it.

You can apply the middleware to a group of routes like this:

Route::middleware('auth:api')->group(function () {

    Route::get(...);
    Route::get(...);
    Route::get(...);
});

Upvotes: 2

Harven
Harven

Reputation: 638

In the subjects route you are not forcing user to be authenticated. You should use Auth::check() to determine if there is authenticated user or not, and then get that user by using Auth::user()

Upvotes: 0

Watercayman
Watercayman

Reputation: 8178

Try replacing ->where('user_id', Auth::id()) with ->where('user_id', Auth::user()->id)

Also, you might not get the object if you are not inside an auth middleware:

Route::group(['middleware' => ['auth']], function () { ... }

Upvotes: 1

Related Questions