How to use Laravel/sanctum in package development

3.1k Views Asked by At

I try to use the Laravel/Sanctum in a custom Laravel package. As in a default Laravel application, I added it to the composer file, added the migration and set it up in the routes file.

The next error message appears:

"Auth guard [sanctum] is not defined."

I hope it is even possible to use sanctum in another package?

Composer.json file:

"require": {
    "php": "7.4.*",
    "laravel/sanctum": "^2.2"
  },

routes file:

Route::group(['middleware' => 'auth:sanctum'], function () {
Route::post('/approve', ['uses' => 'MemberRequestController@response', 'response' => 'approve'])->name('approve_member_request');
}

ServiceProvider

/**
     *
     */
    private function registerRoutes()
    {
        Route::group($this->routeConfig(), function () {
            $this->loadRoutesFrom(__DIR__ . '/../../routes/api.php');
        });
    }

    /**
     * @return string[]
     */
    private function routeConfig(): array
    {
        return [
            'prefix' => ums::path(),
            'namespace' => 'martijn\UMS\Http\Controllers',
            'middleware' => ['api', 'auth:sanctum']
        ];
    }
4

There are 4 best solutions below

1
Lenny On BEST ANSWER

You should publish the Laravel\Sanctum\SanctumServiceProvider.

It will register the missing guard.

0
Giorgi Metonidze On

In my case problem was in RouteServiceProvider, default sign in was redirecting to RouteServiceProvider::HOME and public const HOME = '/dashboard'; Which I didn't had anymore, so replace it just with existing view.

0
CodeToLife On

Started work after me removed content of folder bootstrap/cache/ manually

No cache/view/routes clearings helped

0
Parsa Samandizadeh On

In my host DirectAdmin, I manually reuploaded vendor folder and after facing this error
Auth guard [sanctum] is not defined
I reuploaded bootstrap folder.
Everything works fine right now.