Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to undefined method Illuminate\Database\Query\Builder::withAccessToken()

This error has come up when I use postman with the api.php file.

Using the documentation example of Laravel 5.4 here is the code in the file.

Route::get('/user', function (Request $request) {
return $request->user() ; })->middleware('auth:api');

In postman I have these settings. Image of postman with accept and Auth settings

It seems really unusual to have these errors as HasApiTokens are in the relevant Models, so what is the problem?

like image 433
Jamie Ross Avatar asked Feb 28 '17 17:02

Jamie Ross


3 Answers

i solved this by adding "use HasApiTokens, Notifiable;" in App/User.php

like image 161
ankit Avatar answered Nov 19 '22 06:11

ankit


The answer is a strange one. I discovered by looking at the projectRoot/config/Auth.php file.

The model i was using for 'user' which is set as default in Laravel was set in under the wrong models folder and models name. See image below. image of auth.php file line 70

As you can see on Line 70 the model has to change to the directory and model name of your user or main model for the authentication to work correctly. This withAccessToken can throw you, but it was an authentication issue.

like image 39
Jamie Ross Avatar answered Nov 19 '22 06:11

Jamie Ross


What did it for me, was directly into the App/User.php User Model add

"use Laravel\Passport\HasApiTokens;"

And directly into de class

"use HasApiTokens, Authenticatable, Authorizable;"

<?php

namespace App;

use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Laravel\Passport\HasApiTokens;

class User extends Model implements AuthenticatableContract, AuthorizableContract
{
    use HasApiTokens, Authenticatable, Authorizable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];
}

In my case I'm using Lumen 5.3, but this solved the problem.

like image 3
Alejandro Jimenez Avatar answered Nov 19 '22 06:11

Alejandro Jimenez