how to change api_token column in token guard

Because you need to change how the user is retrieved out of the database, you actually need to create and use a custom UserProvider, not a custom Guard. You'll only need the custom guard if you feel like renaming the input key or storage key from api_token.

So, you'll need a new custom UserProvider class that knows how to retrieve your user with the given credentials (token), and you'll need to tell Auth to use your new custom UserProvider class.

First, assuming you're still using Eloquent, start by creating a new UserProvider class that extends the base EloquentUserProvider class. In this example, it is created at app/Services/Auth/MyEloquentUserProvider.php. In this class, you will need to override the retrieveByCredentials function with the details on how to retrieve the user with the provided token.

namespace App\Services\Auth;

use Illuminate\Auth\EloquentUserProvider;

class MyEloquentUserProvider extends EloquentUserProvider
{
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return;
        }

        // $credentials will be an array that looks like:
        // [
        //     'api_token' => 'token-value',
        // ]

        // $this->createModel() will give you a new instance of the class
        // defined as the model in the auth config for your application.

        // Your logic to find the user with the given token goes here.

        // Return found user or null if not found.
    }
}

Once you've created your class, you need to let Auth know about it. You can do this in the boot() method on your AuthServiceProvider service provider. This example will use the name "myeloquent", but you can use whatever you want (except "eloquent" and "database").

public function boot()
{
    $this->registerPolicies();

    Auth::provider('myeloquent', function($app, array $config) {
        return new \App\Services\Auth\MyEloquentUserProvider($app['hash'], $config['model']);
    });
}

And finally, you need to tell Auth to use your new myeloquent user provider. This is done in the config/auth.php config file.

'providers' => [
    'users' => [
        'driver' => 'myeloquent', // this is the provider name defined above
        'model' => App\User::class,
    ],
],

You can read more about adding custom user providers in the documentation here.


Since the version Laravel 5.7.28, You can simply set up in config/auth.php.

'guards' => [
    'api' => [
        'driver' => 'token',
        'input_key' => 'token',   // The input name to pass through
        'storage_key' => 'token', // The column name to store in database
        'provider' => 'users',
    ],
],