Java, Python, Database, Flutter, Matlap, Micorcontroller, Tutorials, Swing Framework

Hancie e-Learning Studio

Learn Java, Learn HTML, CSS, PHP, Javascript, Python Tutorials || Download program source codes || Java Project and Source code available here || All types error troubleshooting tips available here

How to create a login API in Laravel?

 


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',
];
}















Welcome all to Hancie e-learning studio
Friends,
I have brought an e-learning platform for you from where you can teach internet, website, programming language, error troubleshooting, etc. Blogger, WordPress templates, themes are available for free on this website, which are not charged for downloading, so that you can earn money by blogging using such templates and this is not a difficult task and this You can do it now. You keep uploading new posts by us and keep taking advantage of this website. The aim of which is to spread the knowledge related to internet, career, web designing and technology to the people and contribute to the development of the country.