【问题标题】:Call to undefined method App\Models\User::createToken()调用未定义的方法 App\Models\User::createToken()
【发布时间】:2021-06-21 09:57:13
【问题描述】:

我是 Laravel 新手,我收到此错误:Call to undefined method App\Models\User::createToken()

Laravel Framework 8.34.0 PHP 7.4.3

我的控制器:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Models\User;

class UserController extends Controller
{
   private $sucess_status = 200;

   public function createUser(Request $request){
       $validator = Validator::make($request->all(),
       [
           'first_name' => 'required',
           'last_name' => 'required',
           'phone' => 'required|numeric',
           'email' => 'required|email',
           'password' => 'required|alpha_num|min:5'
       ]
    );

        if($validator->fails()){
            return response()->json(["validattion_errors"=>$validator->errors()]);
        }

        $dataArray = array(
            "first_name"=>$request->first_name,
            "last_name"=>$request->last_name,
            "full_name"=>$request->first_name . " " . $request->last_name,
            "phone"=>$request->phone,
            "email"=>$request->email,
            "password"=>bcrypt($request->password),

        );

        $user = User::create($dataArray);
        if(!is_null($user)){
            return response()->json(["status" => $this->sucess_status, "success" => true, "data" => $user]);
        }else {
            return response()->json(["status" => "failed", "success" => false, "message" => "User not created"]);
        }
   }

   public function userLogin(Request $request){
       $validator = Validator::make($request->all(),
       [
           'email' => 'required|email',
           'password' => 'required|alpha_num|min:5'
       ]
    );

    if($validator->fails()){
        return response()->json(["validation_errors"=>$validator->errors()]);
    }

    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        $user = Auth::user();
        $token = $user->createToken('token')->accessToken;
        return response()->json(["status" => $this->sucess_status, "success" => true, "login" => true, "token" => $token, "data" => $user]);
    } else{
        return response()->json(["status" => "failed", "success" => false, "message" => "Invalid email or password"]);
    }
   }

   public function userDetail(){
       $user = Auth::user();
       if(!is_null($user)){
        return response()->json(["status" => $this->sucess_status, "success" => true, "user" => $user]);
       }else {
        return response()->json(["status" => "failed", "success" => false, "message" => "No user found"]);
    }
   }
}

我的 Auth.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

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

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

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

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

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

我已经运行了 3 次 php artisan passport: install 命令 因为我忘了用设置保存文件,我认为保存文件后有必要再次运行代码

然后返回给我:

Encryption keys already exist. Use the --force option to overwrite them.
Personal access client created successfully.
Client ID: 3
Client secret: JoZbAGCSOZ6t0hn7YnnT6PdN4EMUUZa7H1vU6Sk2
Password grant client created successfully.
Client ID: 4
Client secret: yAxjrBnvPWCiAdXod5FmJDQTNDmneRoO1LtM6B0x
cristiansto in Laravel/API/todoList 
❯ php artisan passport:install --force
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 5
Client secret: 8CtWyvXIwapZnfO5dTGDsyF0iXvJsxNyiZeUksTL
Password grant client created successfully.
Client ID: 6
Client secret: 9jThPxOfgNxJINFKIbDz0WU5yYEup0pIkboEJLr0
cristiansto in Laravel/API/todoList 

不知道是不是这个原因。

会是什么?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    方法 createToken 在 HasApiTokens 特征中,你应该在你的用户模型中使用它 :

     use Laravel\Passport\HasApiTokens;
    
      class User extends Authenticatable
        {
        use HasApiTokens;
        }
    

    【讨论】:

      【解决方案2】:

      我发现了问题,我不得不提出

      use Laravel\Passport\HasApiTokens; 在 User.php 中

      然后

      use HasFactory, Notifiable, HasApiTokens;

      【讨论】:

        猜你喜欢
        • 2021-04-15
        • 2022-12-09
        • 1970-01-01
        • 2023-02-06
        • 2021-03-19
        • 2021-06-24
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        相关资源
        最近更新 更多