【问题标题】:Auth::user() Trying to get property of non-object when test REST API from PostmanAuth::user() 在从 Postman 测试 REST API 时尝试获取非对象的属性
【发布时间】:2017-08-10 15:34:04
【问题描述】:

当我从邮递员测试我的 REST API 时,它给了我错误

Trying to get property of non-object 

因为邮递员没有会话。如果有浏览器,则创建会话但不在邮递员中。任何人都可以提供Auth::user()的替代解决方案

这是我的路线

Route::post('playlist/{id}/follow', 'PlaylistController@follow');

这是我的代码 sn-p。

public function follow($id)
{
     $user = $this->model->findOrFail($id);
     if ($user->id != Auth::user()->id) {
          Auth::user()->followedUsers()->attach($id);
     }
}

【问题讨论】:

  • 你用auth:api保护你的路线吗?
  • 不,我没有保护。
  • 您能否说明您要使用api session 还是web session?
  • 是的,我想使用 api 会话。
  • 你需要它来让 Auth 中间件处理其余的事情。

标签: laravel api postman


【解决方案1】:

在您的User 表中创建一个名为api_token 的列,并添加中间件auth:api 下的所有路由。

然后尝试从Headers 中的邮递员发送api_token 值,例如 -

Authorization Bearer: <api_token_here>

Authorization是标头名称,其值为Bearer: &lt;api_token_here&gt;

那么您的Auth::user()-&gt;id 将按预期工作。

【讨论】:

    【解决方案2】:

    尝试像这样改变你的功能: (我假设你的模型是用户)

     public function follow(User $id)
        {
             if ($id->id != Auth::user()->id) {
                  Auth::user()->followedUsers()->attach($id);
             }
        }
    

    【讨论】:

    • 为什么要投反对票?你的错误在这里$this-&gt;model-&gt;findOrFail($id)你的函数现在不是你指的是哪个模型
    • Postman 没有创建任何会话,这就是发生此错误的原因。所以,伙计,我只想要 Auth::user() 的替代解决方案,因为当我们从邮递员测试我们的 api 时,Auth::user() 不起作用。
    猜你喜欢
    • 2020-06-24
    • 2018-03-07
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多