简体   繁体   中英

Laravel: Auth guard [sanctum] is not defined

I'm trying to implement auth in Laravel via Sanctum . I did all steps from documentation. Generation of Token works fine but when I try to use auth:sanctum middleware it returns the error Auth guard [sanctum] is not defined.

Here are my files:
/routes/api.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Dashboard;


Route::middleware('auth:sanctum')->get('/dashboard/get_current_client/', [Dashboard::class, 'get_current_client']);

Route::get('/dashboard/client_data/', [Dashboard::class, 'client_data']);

/config/auth.php

<?php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Client::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],


    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    'password_timeout' => 10800,

];

/app/Models/Client.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;



class Client extends Authenticatable
{
    use HasFactory, HasApiTokens, Notifiable;

    protected $table = 'client';
    protected $primaryKey = 'client_id';
    public $timestamps = false;
}

/app/Http/Controllers/Dashboard.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Client;



class Dashboard extends Controller
{
    public function client_data () {
        $user = Client::where('client_id', 1)->first();
        return $user->client_id;
    }

    public function get_current_client(Request $request) {
        var_dump($request->user());
    }
}

I found the problem. For some reason cache in /bootstrap/cache has not updated. After manual removing it, everything started working.

to fix it add the below code to file " /bootstrap/cache/packages.php "

'laravel/sanctum' => array (
'providers' => 
array (
  0 => 'Laravel\\Sanctum\\SanctumServiceProvider',
), ),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM