Laravel 护照抛出错误:“在 null 上调用成员函数 createToken()”
Posted
技术标签:
【中文标题】Laravel 护照抛出错误:“在 null 上调用成员函数 createToken()”【英文标题】:Laravel passport throwing error: 'Call to a member function createToken() on null' 【发布时间】:2019-12-04 06:53:56 【问题描述】:所以我正在尝试使用 phpunit 创建身份验证存储库测试,但我不断收到错误“调用 null 时的成员函数 createToken()”。我认为这是由于 RefreshDatabase 特性,但我正在安装护照,所以我有点迷路了。任何帮助表示赞赏!
AuthRepository 测试
namespace Tests\Repository;
use App\Contracts\Auth;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class AuthRepositoryTest extends TestCase
use RefreshDatabase;
protected $authRepository;
protected function setUp(): void
parent::setUp();
$this->artisan('passport:install');
$this->authRepository = app()->make(Auth::class);
/**
* Test Successful Login
*
* @return void
*/
public function testSuccessfulLogin(): void
$request = new \Illuminate\Http\Request();
$request->setMethod('POST');
$request->replace(['name' => 'test', 'email' => 'test', 'password' => 'testing']);
$this->authRepository->register($request);
$request = new \Illuminate\Http\Request();
$request->setMethod('POST');
$request->replace(['email' => 'test', 'password' => 'testing']);
$this->authRepository->login($request);
测试用例
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
use CreatesApplication;
protected function setUp(): void
parent::setup();
AuthRepository
<?php
namespace App\Repositories;
use App\Contracts\Auth;
use Illuminate\Support\Facades\Auth as Authenticate;
use App\User;
class AuthRepository implements Auth
public function Register($request)
$user = new User([
'name' => $request->input('name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password'))
]);
$user->save();
return $user;
public function Login($request)
$credentials = $request->all();
if (!Authenticate::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
$token->save();
return $tokenResult;
【问题讨论】:
【参考方案1】:这是因为控制器试图获取用户数据并基于该数据创建令牌。
在您的情况下(也发生在我身上),有一个用户变量指向获取用户凭据的请求,而用户数据未知,因为用户尚未登录。
为了清楚起见,请查看您在这一行中的代码:
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
要解决这个问题,请将$user = $request->user()
的行更改为:
$user = User::whereEmail($request->email)->first();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
【讨论】:
以上是关于Laravel 护照抛出错误:“在 null 上调用成员函数 createToken()”的主要内容,如果未能解决你的问题,请参考以下文章
致命错误:允许的内存大小为 1610612736 字节用尽 laravel 护照