Laravel Sanctum Way To Authenticates different Models rather than Users.

·

1 min read

Laravel Sanctum is one way to authenticate different models to use your application but there are many other ways.

In this article, I'll be explain how to authenticate team/team members with a Laravel Sanctum.

Assume that we have following Model;

class Team extends Model { ... }

If we add Laravel Sanctum's Trait "use HasApiTokens" then we can easily use all API authentication features on Team model too.

class Team extends Model
{
    use HasApiTokens;
}

From now on, we are ready to authenticate Team Model.

Create an API token to use for that Team Model;

$team = Team::query()->find(1);
$token = $team->createToken('debug-token', ['all'])->plainTextToken; // save plain Text token to use later on.

Let's have a create an API route in api.php;

Route::post('authenticate/team', function (Request $request) {
    return $request->user(); // this is going to return the Team not User Model
})->middleware('auth:sanctum');

Be careful about adding 'auth:sanctum' middleware to the route otherwise it will not work.

Now let's have a try it sending a request to this API using Postman; Always include plain text token in the header as a Bearer Token.

Now it's good and we could access to the team.