php - Laravel 5.5 试图获取非对象的属性 'id'

标签 php mysql laravel laravel-5

我是 Laravel 的新手。我使用的是 Laravel 5.5 版

如果我尝试使用 postman 登录。我收到“试图获取非对象的属性‘id’”错误。错误行是

    private $client;

public function __construct(){
    $this->client = Client::find(1);
}

public function login(Request $request){

    $this->validate($request, [
        'username' => 'required',
        'password' => 'required'
    ]);

    return $this->issueToken($request, 'password'); // this line has error

}

issueToken 函数
public function issueToken(Request $request, $grantType, $scope = ""){

    $params = [
        'grant_type' => $grantType,
        'client_id' => $this->client->id,
        'client_secret' => $this->client->secret,           
        'scope' => $scope
    ];

    if($grantType !== 'social'){
        $params['username'] = $request->username ?: $request->email;
    }

    $request->request->add($params);

    $proxy = Request::create('oauth/token', 'POST');

    return Route::dispatch($proxy);

}

我在注册时遇到了同样的错误。但是我的用户成功注册了 500 错误(试图获取非对象的属性“id”)

最佳答案

错误是因为 $this->clientfind() 时为空找不到记录。

您需要确定该记录是否存在。

更改:

$this->client = Client::find(1);

至:
$this->client = Client::findOrFail(1);

文档:

来自 Laravel Eloquent docs ,
这将抛出 404如果未找到具有指定 id 的记录,则出错。

关于php - Laravel 5.5 试图获取非对象的属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48422199/

相关文章:

php - 如何计算 sphinx 的结果?

php - 如何允许登录的用户更新/编辑他们的个人资料设置/信息

javascript - 在表单上显示表单验证

php - 如何处理 Laravel Eloquent "WHERE"Query with slash on the value? (拉拉维尔 5.3)

php - 在 PHP 中调试 SQL 语法错误

php - 如何在 PHP 中解析 OFX(版本 1.0.2)文件?

php - Laravel 5.8 自定义表单请求未按预期工作?

mysql 加入 ON 和 AND 到 laravel Eloquent

mysql - sphinx 和一对多关联

mysql - 使用过程变量创建服务器端准备好的语句 - MySQL