api.php
Route::post('/login',[AuthController::class,'login']);
AuthController.php
public function login(LoginRequest $request)
{
$credentials = $request->only('email', 'password');
try {
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('login_token')->accessToken;
return responseSuccess(['data' => $user,
'token' => $token], 200, "You have login successfully!");
} else {
return responseError("Wrong Email and Password!", 500);
}
} catch (\Exception $e) {
return responseError($e->getMessage(), 500);
}
}
LoginRequest.php
public function rules(): array
{
return [
'email' => ['required'],
'password' => ['required']
];
}
User.php
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
use HasRoles;
const ADMIN='admin';
protected function getDefaultGuardName(): string { return 'api'; }
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'status'
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}