【问题标题】:Laravel 5.5 Trying to get property 'id' of non-objectLaravel 5.5 试图获取非对象的属性“id”
【发布时间】:2018-07-03 11:33:43
【问题描述】:

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

如果我尝试使用邮递员登录。我得到“尝试获取非对象的属性 '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->clientnull
  • 对不起,我忘记了。添加了 $client 变量
  • 显示 dd($this->client)
  • null @Sohel0415 我如何填写 $this->client.我用视频学习 laravel。我对视频应用相同的操作。有什么问题?
  • 您有 id 为 1 的客户吗??

标签: php mysql laravel laravel-5


【解决方案1】:

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

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

更改:

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

收件人:

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

文档:

来自Laravel Eloquent docs, 如果没有找到具有指定 id 的记录,这将引发 404 错误。

【讨论】:

    【解决方案2】:

    当我尝试访问我的项目数据库中不存在的 id 时,我遇到了同样的问题。这个$user= user::findOrFail($id); 解决了我的问题。

    【讨论】:

      【解决方案3】:

      在您的issueToken() 方法中-

      $client = Client::find(1);
      if($client!=null){
           $params = [
             'grant_type' => $grantType,
             'client_id' => $client->id,
             'client_secret' => $client->secret,           
             'scope' => $scope
          ];
      }else{
          $params = [
             'grant_type' => $grantType,
             'client_id' => null,
             'client_secret' => null,           
             'scope' => $scope
          ];
      }
      

      【讨论】:

        【解决方案4】:

        确保数据库表中有 ID = 1 的用户模型的记录。当您使用 User::find(1) 时,Laravel 尝试从数据库中获取此记录,如果记录不存在,则返回 null

        【讨论】:

        • 检查 oauth_clients 表并检查记录 id 1,它必须存在才能正常工作
        猜你喜欢
        • 2018-06-06
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        • 2021-05-26
        • 2018-02-10
        • 1970-01-01
        • 2020-06-26
        • 1970-01-01
        相关资源
        最近更新 更多