John Davidson

php - laravel 8 - auth()->factory() { same refresh() and attemp() } is undefind in JWT AuthController

0 comments
Message:


I use JWT for API authentication in Laravel 8.


When I use auth()-> in my controller , for factory() or attemp() or anything, Laravel does not know it and says:


Undefined method 'attempt'.intelephense(1013)


I don't know what I forgot to include


my AuthController :


namespace App\Http\Controllers\Api\Admin;

use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{

public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}


public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);

if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}

if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->createNewToken($token);
}
.
.
.
.
.

and my config/auth.php file :


return [

'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],


'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],

'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],


'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// Following array is newly added to config
'otp-user' => [
'driver' => 'otp-based-auth-provider'
],


'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],


'password_timeout' => 10800,

];




My Answer:
In Laravel 8, the `auth()` function is used to check if a user is authenticated or not. It returns an instance of the currently authenticated user or null if the user is not authenticated.

Here is an example of how you can use the `auth()` function in a Laravel 8 application:

php
use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
// User is authenticated
$user = Auth::user();
echo 'Welcome, ' . $user->name;
} else {
// User is not authenticated
echo 'Please log in to access this page';
}


You can also use the `auth()` function to perform various authentication-related tasks such as logging in a user, logging out a user, checking if a user is authenticated, etc.

For more information on Laravel authentication, you can refer to the official Laravel documentation: https://laravel.com/docs/8.x/authentication

Rate this post

3 of 5 based on 9151 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us