Когда я пытаюсь изменить пользователей таблицы, это по умолчанию связано с Auth в laravel, мой API всегда дает мне ответ «неавторизованный пользователь», и когда я использую пользователя таблицы по умолчанию, он работает нормально. Я хочу знать, почему это происходит?
Я внес все изменения, необходимые для переключения таблицы с пользователей на таблицу выбора.
имя моей таблицы: apitable , Имя модели: apitablemodel
изменения в аутентификации. php:
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'api',
'Passwords' => 'apitable', //if want to change the table attached with auth then make changes here
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session", "token"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'apitabel',
],
'api' => [
'driver' => 'passport',
'provider' => 'apitable',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'apitable' => [
'driver' => 'eloquent',
'model' => App\apitablemodel::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expire time is the number of minutes that the reset token should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'apitable' => [
'provider' => 'apitable',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Вот мой файл модели
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
// use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class apitablemodel extends Authenticatable
{ use HasApiTokens, Notifiable;
//
protected $table='apitable';
protected $fillable = ['Email', 'Password','token'];
public $timestamps=false;
protected $hidden = [
'Password', 'token',
];
}
Вот мой файл контроллера
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\apitablemodel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
// response()->json(['success' => $success], $this-> successStatus);
class product extends Controller
{ public $successStatus = 200;
public function login(Request $request){
if(Auth::check(['Email' => request('Email'), 'Password' => request('Password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function update(Request $req){
$obj= User::find($req->id);
$obj->email=$req->email;
if($obj->save()){
return response()->json(['success'=>'Updated']);
}
else{
return ["status:"=>"Unauthorized user, make sure your are login"];
}
}
}
У меня в контроллере две функции: одна предназначена для обновления данных, присутствующих в таблице «apitable», а другая для входа в систему, чтобы только аутентифицированные пользователи могли обновите значения таблицы базы данных.
Когда я нажимаю мой API в почтальоне, он дает мне неавторизованный ответ, для которого я записал условие в моем контроллере. Я хочу знать, почему, если условие не выполняется.